【问题标题】:Passing data to nested component with ngFor使用 ngFor 将数据传递给嵌套组件
【发布时间】: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


【解决方案1】:

[]{{}} 不能永远一起使用。

随便用

[name]="cComponent.name"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-06
    • 2018-11-12
    • 2018-02-02
    • 1970-01-01
    相关资源
    最近更新 更多