具有动态值的ngTemplateOutlet

Swa*_*ski 11 angular

我正在使用具有动态值的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>
Run Code Online (Sandbox Code Playgroud)
  • config对象在哪里
  • config[part]布尔值在哪里
  • 哪里part是目标的关键,并传递给ngTemplateOutlet值.

我总是得到错误:

ERROR TypeError: templateRef.createEmbeddedView is not a function
Run Code Online (Sandbox Code Playgroud)

我跟着:https://stackoverflow.com/a/41241329/5627096

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

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

这是一个非常大的形式,为了更好的阅读,我正在寻找一个分裂它的解决方案.

UPDATE

config对象看起来像:

config = {
    one: true,
    two: false
}
Run Code Online (Sandbox Code Playgroud)

所以在我的表单中只<ng-template #one></ng-template>显示了.如果我将两个转为true,则显示两者.

我不知道这是不是最好的方法.我可以使用*ngIf,但是使用这个解决方案,我真的无法读取大代码.

Gün*_*uer 17

将这些添加到components类

@ViewChild('one') one:TemplateRef<any>;
@ViewChild('two') two:TemplateRef<any>;
Run Code Online (Sandbox Code Playgroud)

并使用获取模板引用

<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>
Run Code Online (Sandbox Code Playgroud)

StackBlitz的例子