ngTemplateOutlet与动态值的使用

14

我正在使用具有动态值的ngTemplateOutlet。

<ng-container *ngFor="let part of objectKeys(config);">
    <ng-container *ngIf="config[part]">
        <ng-container [ngTemplateOutlet]="part"></ng-container>
    </ng-container>
</ng-container>

<ng-template #one></ng-template>
<ng-template #two></ng-template>
  • 其中config是一个对象
  • config[part]是一个布尔值
  • part是对象的键,并且是传递给ngTemplateOutlet的值。

我总是得到错误:

ERROR TypeError: templateRef.createEmbeddedView is not a function

我已经遵循了:https://dev59.com/RZvga4cB1Zd3GeqP2HMO#41241329

但也许我不能做那样的事情。

实际上,配置对象包含布尔值,就像我说的那样,并定义要显示的表单部分。

这是一个非常大的表格,为了更好的阅读,我正在寻找一种将其拆分的解决方案。

更新

配置对象看起来像:

config = {
    one: true,
    two: false
}

因此,在我的表单中只显示<ng-template #one></ng-template>。如果我将two更改为true,则两者都会显示。

我不知道这是否是最佳方法。我可以使用*ngIf,但是使用这种解决方案会使我的代码非常难以阅读。

2个回答

23
请将以下内容添加到组件类中。
@ViewChild('one') one:TemplateRef<any>;
@ViewChild('two') two:TemplateRef<any>;

使用以下方法获取模板的引用

<form no-validate (ngSubmit)="onSubmit(search)">
    <ng-container *ngFor="let part of objectKeys(config);">
        <ng-container *ngIf="config[part]">
            <ng-container [ngTemplateOutlet]="this[part]"></ng-container>
        </ng-container>
    </ng-container>
</form>

StackBlitz示例


1
谢谢,但是ngOutletContext是用来在<ng-template>内传递数据的,对吧?我想要的是对<ng-template>的引用。我的意思是,如果part = one,那么就会显示<ng-template #one></ng-template>。 - Swarovski
我认为你需要使用我之前评论中提到的 @ViewChild() 代码,并在 *ngFor 中使用 this[config[part]](不确定)。如果你创建一个 https://stackblitz.com/ 或 Plunker 来重现问题,我可以更仔细地查看。 - Günter Zöchbauer
1
谢谢Günter,我已经更新了您的帖子,使其按照我的要求工作。这是最新的可用代码:https://stackblitz.com/edit/angular-2txidk?file=app%2Fapp.component.css - Swarovski
1
太棒了!我成功解决了我的问题!! https://dynamic-template-outlet.stackblitz.io - Sampgun
1
@tom,它是组件类的“this”,例如this.one,其中one@ViewChild('one') one:TemplateRef<any> - galki
显示剩余8条评论

0
  • 通过将动态值传递给ngTemplateOutlet指令来呈现模板引用
  • 使用属性绑定来传递存储在templateRefs数组中的模板引用的引用

.ts文件

export class RenderTemplateRefsInNgTemplateOutletDirective {
  @ViewChild('one', { static: false }) one:TemplateRef<any>;
  @ViewChild('two', { static: false }) two:TemplateRef<any>;
  @ViewChild('three', { static: false }) three:TemplateRef<any>;

  templateRefs: Array<TemplateRef<any>> = [];

  config: any = {
    'one': true,
    'two': false,
    'three': true,
  }

  objectKeys = Object.keys;

 ngAfterViewInit() {
  const values = Object.keys(this.config).filter(key => this.config[key]);
  values.forEach(key =>{
    this.templateRefs.push(this[key]); // accessing **this** component ViewChild 
                                      // with same **name** defined as `key` in forEach
  })
 }
}

.html

<ng-container *ngFor="let template of templateRefs">
    <ng-container [ngTemplateOutlet]="template"></ng-container>
 </ng-container>
 
 <ng-template #one>
 <h1>Hello One</h1>
 </ng-template>
 
 <ng-template #two>
   <h1>Hello Two</h1>
 </ng-template>
 
 <ng-template #three>
   <h1>Hello Three</h1>
 </ng-template>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接