【问题标题】:Angular ng-content: how to use parents data as children inputAngular ng-content:如何使用父数据作为子输入
【发布时间】:2019-02-13 00:38:44
【问题描述】:

我有一个使用<ng-content></ng-content> 的组件,并且该组件本身有一些数据应该传递给<ng-content></ng-content> 标签内的任何组件。

使用 ngContent 的组件:

parent.component.ts

class ParentComponent {
    data;
}

parent.component.html

<p>Data:</p>
<ng-content><ng-content>

应该进入使用 ngContent 的组件内部的组件:

child.component.ts

class ChildComponent {
    // I need this to be passed from parent component
    @Input() data; 
}

child.component.html

<ul>
    <li *ngFor="let element of data">{{ element.name }}</li>
</ul>

所需用途:

view.component.html

<parent-component>
    <child-component [data]="data"></child-component>
</parent-component>

有没有办法让child-component 的输入[data] 来自parent-component?我在个人项目中尝试过这种方法,但我得到一个空列表,不知何故没有通过。

【问题讨论】:

  • 你试过什么? &lt;parent-component #parent&gt; &lt;child-component [data]="parent.data"&gt; 会为你工作吗?
  • @yurzui 我尝试了你在问题帖子中看到的内容,我会看看你的建议。
  • @yurzui 我可以尝试一下并为我工作!

标签: javascript angular components


【解决方案1】:

使用template reference variables 可以实现最接近您所需用途的解决方案:

<parent-component #parent>
  <child-component [data]="parent.data"></child-component>
</parent-component>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-08
    • 2021-04-21
    • 1970-01-01
    • 1970-01-01
    • 2021-05-07
    • 2018-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多