【问题标题】:Angular passing object to child component角度将对象传递给子组件
【发布时间】:2020-11-02 05:28:48
【问题描述】:

我有一个这样的 ngFor 指令:

<div *ngFor="let data of datas|slice:0:2"><app-data [data]="data"></app-data></div>

但是数据对象并没有从封闭的 div 传递到 app-data 组件中。

如何将数据从 div 传递到 app-data?

【问题讨论】:

  • 这应该可行,您是否尝试过控制台记录数据对象?
  • 我得到一个 NaN。甚至没有未定义。
  • 请分享您定义data的代码
  • @Latcie 请检查我的以下答案,如果你清楚我的答案,投票并标记为好答案,它将对其他人有所帮助。

标签: angular


【解决方案1】:

父组件


您可以使用简单

例如我有这样的父组件

<div *ngFor="let data of datas|slice:0:2">
    <app-child [data]="data"></app-child>
</div>

TS

我有虚拟数组

 datas = [
    {id: 1, name: 'ABC'},
    {id: 2, name: 'EFG'}
  ];

子组件


现在你可以使用这个数组来子组件像这样

HTML

<ul>
    <li>{{data.id}}</li>
    <li>{{data.name}}</li>     
</ul>

TS

// This will bring data from parent component and this is used for sharing data between parent context and child directives or components
@Input() data;

ngOnInit() {
  console.log('data => ', this.data);
}

我的例子你可以查看Here

【讨论】:

    猜你喜欢
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    • 2020-03-04
    • 2017-11-14
    • 1970-01-01
    • 2019-04-02
    • 1970-01-01
    相关资源
    最近更新 更多