【发布时间】:2017-11-10 12:47:12
【问题描述】:
我有一个父组件 (ParentComponent),它的 html 有几个子组件 (ChildComponent)。显示的子组件数量取决于使用 ngFor 的数组的长度。我试图弄清楚如何在模板中的每个子组件上设置一个属性。
这是我的 ParentComponent html:
<div>
<p-panel header="Parent Component Manager">
<p-panel header="ChildComponents">
<childComponent *ngFor="let cComponent of cComponentsArray" [name]="childComponentTitle">
</childComponent>
</p-panel>
</p-panel>
</div>
我的 ParentComponent.component.ts 文件包含(我想停止使用它并使用 cComponentsArray 中的字符串值:
childComponentTitle: string = "This text is passed to child."
我的 ChildComponent html:
<p-accordion [multiple]="true">
<p-accordionTab header="ChildComponent name: {{name}}">
<h4>Random text</h4>
<h4>Random text</h4>
</p-accordionTab>
</p-accordion>
我的 ChildComponent.component.ts 文件包含:
@Input() name: string;
使用上面的当前代码,这会将每个子组件的“名称”属性设置为相同的东西。我想根据 cComponentsArray 的 cComponent 中包含的字符串值来设置它。
我已经尝试在 ParentComponent.html 中使用
[name] = {{cComponent.name}}
没有任何运气。有人可以向我解释我做错了什么以及如何正确实施吗?
【问题讨论】:
-
如果
cComponent.name包含您要传递的值,[name] = {{cComponent.name}}应该可以工作。 -
@GünterZöchbauer 感谢您的回复。使用它时,我得到一个模板解析错误:Unexpected token {, expected identifier, keyword, or string at column 2 in [{{cComponent.name}}]
-
对,那是无效的。
[]和{{}}不能永远一起使用。只需使用[name]="cComponent.name"
标签: html angular typescript data-binding