我有一个在ngFor循环中使用子组件的组件。该子组件有一个使用@Input
读取的数据绑定。
我面临的问题是,当我将数据推送到子组件时,子组件的每个实例都会获得相同的值。有没有办法只推送ngFor中子组件bind的特定实例的数据?
Here is a dummy example I created
当我单击第一个按钮时,我希望它以这种方式工作,只有第一个子组件应该获得值,但第二个组件应该是空的。
我在angular环境中是新手,所以任何帮助都会很好。
发布于 2020-03-29 16:00:17
pushToChild
将在孩子之间共享,所以我们不使用它。我能想到的最简单的方法是使用子DOM元素将值直接传递给子元素,该元素转换为变量声明(#child
),这在循环遍历时是唯一的。
.ts
import { Component } from '@angular/core';
import { ChildComponent } from './child-component/child.component';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
object: { [key: number]: string } = { 2: 'foo', 1: 'bar' };
push(value: any, child: ChildComponent) {
child.data = value;
}
}
.html
<span>
<p>Some dummy list</p>
<div *ngFor="let item of object | keyvalue"
style="background:gray; margin-top:0.5rem">
Click button to push value: {{ item.key }} to child
<button (click)="push(item.key, childRef)">Push</button>
<child-component #childRef></child-component>
</div>
</span>
https://stackoverflow.com/questions/60916638
复制相似问题