我使用的是具有动态值的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://stackoverflow.com/a/41241329/5627096
但也许我不能做那样的事。
实际上,config对象包含布尔值,就像我说的那样,并定义要显示的窗体的部分。
这是一个很大的形式,为了更好的阅读,我正在寻找一个解决方案来分割它。
更新
config对象如下所示:
config = {
one: true,
two: false
}因此,在我的表单中,只显示了<ng-template #one></ng-template>。如果我将两次转换为真,则都会显示出来。
我不知道这是不是最好的方法。我可以使用*ngIf,但是有了这个解决方案,我的代码真的很难读。
发布于 2017-10-01 14:59:00
将这些添加到components类中
@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>发布于 2020-06-27 00:58:35
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>https://stackoverflow.com/questions/46513603
复制相似问题