我正在尝试使用 Angular 2 创建一个表单生成器。一个非常基本的示例如下:
this.fields = [{name: 'Name', type: 'text'}, {name: 'Age', type: 'number'}];
但我也想支持自定义元素,例如:
this.fields = [
{name: 'Name', type: text},
{name: 'Age', type: 'custom', customid: 'Ctl1'},
{name: 'Whatever', type: 'custom', customid: 'Ctl2'}
];
// template:
<super-form [fields]="fields">
<Ctl1><input type="number" ...><Ctl1>
<Ctl2><whaterver-control ...><Ctl2>
</super-form>
在我的表单生成器组件中,我有类似的内容:
<div *ngFor="let f of fields">
<div [ngSwitch]="f.type">
<span *ngSwitchWhen="'custom'">
<ng-content select="f.customid"></ng-content>
</span>
</div>
</div>
但考虑到我在这里,这显然行不通。这是 ng2 的限制吗?如果是这样,我想我可以对 5 个可选内容元素进行硬编码,并检查它们是否已指定并且没有动态选择,但这是一个 hack。
Cheers
我知道这是一个老问题,但这是我在搜索此功能时首先想到的地方之一,因此我将添加我如何解决它的方法。
ngContent 仅用于静态投影,因此您不能使用它进行任何绑定。如果您需要在投影内容中进行绑定,您可以使用 ngTemplateOutlet 和 ngOutletContext。
使用示例:
<my-component>
<template let-item="item">
<h1>{{item?.label}}</h1> - <span>{{item?.id}}</span>
</template>
</my-component>
在 MyComponent 中,您可以使用 ContentChild 访问该模板:
@ContentChild(TemplateRef) templateVariable: TemplateRef<any>;
然后在组件的模板中将其传递给 ngTemplateOutlet,如下所示:
<div *ngFor="let item of list">
<template [ngTemplateOutlet]="templateVariable" [ngOutletContext]="{item: item}"></template>
</div>
ngOutletContext 是可选的,但它允许您创建将在模板中绑定到的对象。请注意,我创建了一个属性item
在上下文对象中。这与我在模板上放置的名称相匹配:let-item="item"
现在的消费者my-component
可以传入用于列表中每个项目的模板。
信用:
这answer https://stackoverflow.com/a/37662335/710268引导我走向正确的方向。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)