如何将字符串转换为模板引用实例?

时间:2019-05-06 08:57:06

标签: angular angular-template-variable

我正在* ngFor中设置ngTemplateOutlet,如下面的代码片段

  <ul>
    <li *ngFor="let item of list">
      <ng-container [ngTemplateOutlet]="item.type"></ng-container>
    </li>
  </ul>

list = [ {type: 'templateOne'}, {type: 'templateTwo'} ]和我定义的模板如下。

<ng-template #templateOne></ng-template>
<ng-template #templateTwo></ng-template>

上面的模板片段抛出错误并显示以下消息

TypeError: templateRef.createEmbeddedView is not a function
    at ViewContainerRef_.push../node_modules/@angular/core/fesm5/core.js.ViewContainerRef_.createEmbeddedView (core.js:21600)
    at NgTemplateOutlet.push../node_modules/@angular/common/fesm5/common.js.NgTemplateOutlet.ngOnChanges (common.js:4026)
    at checkAndUpdateDirectiveInline (core.js:22085)

由于item.type中使用的ngTemplateOutlet是字符串类型,我怀疑它无法解析为templateReference变量。

如何将字符串转换为templateReference实例?

演示-See this link for example and verify console for the error

3 个答案:

答案 0 :(得分:0)

这是工作示例:

    import { Component,ViewChild,TemplateRef,OnInit } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
  <ul>
     <li *ngFor="let item of list;let i = index">
      <ng-container [ngTemplateOutlet]="list[i].type"></ng-container>
    </li>
  </ul>
  <ng-template #templateOne>Template One</ng-template>
  <ng-template #templateTwo>Template Two</ng-template>
  `,
})
export class AppComponent  implements OnInit {
  @ViewChild('templateTwo', {read: TemplateRef}) tpl1: TemplateRef<any>;
  @ViewChild('templateOne', {read: TemplateRef}) tpl2: TemplateRef<any>;
  list;

    ngOnInit() {
      this.list=[{"type":this.tpl1},{"type":this.tpl2}];
    }

}

Reference link

Working example stackblitz

答案 1 :(得分:0)

您的问题实际上是我们如何将字符串视为模板html中的templateReferance变量。 如果您不必那样处理,则可以尝试以下方法:

 @ViewChild('templateOne') templateOne: ElementRef;
 @ViewChild('templateTwo') templateTwo: ElementRef;
  list;
  ngOnInit() {
    this.list = [ {type: this.templateOne}, {type: this.templateTwo} ];
  }

答案 2 :(得分:0)

基本上,您可以创建执行映射/转换的纯函数:

curl

模板:

public map(type:string, ref1:TemplateRef, ref2:TemplateRef):TemplateRef {
   switch(type) {
      case 'templateTwo':
        return ref1;
      case 'templateTwo':
        return ref2;
      default:
        return ref1;
   }
}

否则,您将需要访问模板<ul> <li *ngFor="let item of list"> <ng-container [ngTemplateOutlet]="map(item.type, templateOne, templateTwo)"></ng-container> </li> </ul>

context