首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >具有动态值的ngTemplateOutlet

具有动态值的ngTemplateOutlet
EN

Stack Overflow用户
提问于 2017-10-01 14:54:30
回答 2查看 20.2K关注 0票数 14

我使用的是具有动态值的ngTemplateOutlet。

代码语言:javascript
复制
<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。

我总是会犯错误:

代码语言:javascript
复制
ERROR TypeError: templateRef.createEmbeddedView is not a function

我跟踪了:https://stackoverflow.com/a/41241329/5627096

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

实际上,config对象包含布尔值,就像我说的那样,并定义要显示的窗体的部分。

这是一个很大的形式,为了更好的阅读,我正在寻找一个解决方案来分割它。

更新

config对象如下所示:

代码语言:javascript
复制
config = {
    one: true,
    two: false
}

因此,在我的表单中,只显示了<ng-template #one></ng-template>。如果我将两次转换为真,则都会显示出来。

我不知道这是不是最好的方法。我可以使用*ngIf,但是有了这个解决方案,我的代码真的很难读。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-10-01 14:59:00

将这些添加到components类中

代码语言:javascript
复制
@ViewChild('one') one:TemplateRef<any>;
@ViewChild('two') two:TemplateRef<any>;

获取模板引用。

代码语言:javascript
复制
<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 example

票数 23
EN

Stack Overflow用户

发布于 2020-06-27 00:58:35

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

.ts文件

代码语言:javascript
复制
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

代码语言:javascript
复制
<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>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46513603

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档