如何在函数内部动态设置模板引用

How to set template reference dynamically inside function

我在下面调用了一个函数 setModelData

我的查询是我想为 getGlobalListgetNonGlobalList 函数创建动态模板变量。

例如

1) 如果 getGlobalList 是 运行 它将设置 模板:this.CustomTableItemTemplatesetModelData 函数中。

2) 如果 getNonGlobalList 是 运行 它将通过 模板:this.NonGlobalCustomTableItemTemplatesetModelData 函数中。

感谢帮助

代码

@ViewChild('CustomTableItemTemplate') CustomTableItemTemplate: TemplateRef<any>;
@ViewChild('NonGlobalCustomTableItemTemplate') NonGlobalCustomTableItemTemplate: TemplateRef<any>;


ngOnInit() {
  this.getGlobalList();
  this.getNonGlobalList();  
}

getGlobalList() {
  this.globalSchemamodel.data.length = 0;

  this.Service.getGlobalList(
    this.constructQueryParam(this.globalSchemamodel, 'global'))
      .subscribe((response: any) => {
        const globalSchemas = response ? response.data : [];
        if (globalSchemas.records) {
          this.setModelData(globalSchemas, this.globalSchemamodel);
        }     
      });
} 

getNonGlobalList() {
  this.nonGlobalSchemamodel.data.length = 0;

  this.Service.getList(
    this.constructQueryParam(this.nonGlobalSchemamodel, 'nonglobal'))
      .subscribe((response: any) => {
        const nonglobalschemaslist = response ? response.data : [];
        if (nonglobalschemaslist.records) {
          this.setModelData(nonglobalschemaslist, this.nonGlobalSchemamodel);
        }     
      });

} 

setModelData(globalSchemas, globalSchemamodel) {
  for (const schema of globalSchemas.records) {
    const tableModel = [
     new TableItem({ data: schema.schema_id }),
       this.isAdminRole ? new TableItem({
       data:[{ 'schemaId': schema.schema_id }],
       **template: this.CustomTableItemTemplate**
     }) : null
    ];
    globalSchemamodel.data.push(tableModel);
  }
}

setModelData 函数肯定需要另一个 template 参数。

此外,您可以从 getNonGlobalListgetGlobalList

中提取类似的代码
ngOnInit() {
  this.getList(
    this.globalSchemamodel,
    this.Service.getGlobalList,
    'global',
    this.CustomTableItemTemplate
  );
  this.getList(
    this.nonGlobalSchemamodel,
    this.Service.getList',
    'nonglobal',
    this.NonGlobalCustomTableItemTemplate
  );  
}

getList(model: any, functionToCall: any, paramName: string, template: TemplateRef<any>) {

  model.data.length = 0;

  functionToCall(
    this.constructQueryParam(model, paramName))
      .subscribe((response: any) => {
        const schemas = response ? response.data : [];
        if (schemas.records) {
          this.setModelData(schemas.records, model);
        }     
      });
} 

setModelData(schemas: any[], schemaModel: any, template: TemplateRef<any>) {
  for (const { schema_id } of schemas) {
    const tableModel = [
      new TableItem({ 
        data: schema_id
      }),
      this.isAdminRole ? new TableItem({
      data: [
        {
          'schemaId': schema_id
        }
       ],
       template
     }) : null
    ];
    schemaModel.data.push(tableModel);
  }
}