具有动态值的ngTemplateOutlet [英] ngTemplateOutlet with dynamic value
问题描述
我正在使用具有动态值的ngTemplateOutlet.
I'm using ngTemplateOutlet with dynamic value.
<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. - Where
config
is an object - Where
config[part]
is a boolean - Where
part
is the key of object and the value passed to ngTemplateOutlet.
我总是会收到错误消息:
I always get the error :
ERROR TypeError: templateRef.createEmbeddedView is not a function
我关注了: https://stackoverflow.com/a/41241329/5627096
但是也许我不能做这样的事情.
But maybe I can't do something like that.
实际上,配置对象包含布尔值(如我所说),并定义了要显示的表单部分.
Actually the config object contains boolean, like I said, and define the part of a form to display.
这是一种很大的形式,为了更好地阅读,我正在寻找一种拆分方法.
It's really big form and for better reading, I'm looking for a solution to split it.
更新
config对象看起来像:
config object looks like :
config = {
one: true,
two: false
}
因此在我的表单中仅显示<ng-template #one></ng-template>
.如果我将两个都设为true,则会同时显示两个.
So in my form only the <ng-template #one></ng-template>
is displayed. If I turn two to true, both are displayed.
我不知道这是否是最好的方法.我可以使用* ngIf,但是使用此解决方案,我的确有无法读取的大代码.
I don't know if it's the best approach. I can use *ngIf but with this solution I have really unreadable big code.
推荐答案
将这些添加到组件类
@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>
这篇关于具有动态值的ngTemplateOutlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!