为什么如果我在同一页面上添加两个组件,这些组件不会"执行"相同的操作? 但只有这个一开始在顶部
喜欢这个:
<h1>Angualr + Material</h1>
<button md-raised-button (click)="addEvent()">Add row for all ... to array</button>
<br><br>
<table-cart [tableData]="tableData"></table-cart>
<br><br>
<span>The same page but other place for example in other tab</span>
<br><br>
<table-cart [tableData]="tableData"></table-cart>
https://plnkr.co/edit/YFL0wdGGXrwtjs4Exrx1?p=preview
原因是您使用的是ViewChild
.它获取指定元素的第一个实例。您需要改用ViewChildren
并遍历所有内容并进行更新。
在您的 plunker 代码中,将
@ViewChild
行更改为:
@ViewChildren(TableCartComponent) tableCarts: QueryList<TableCartComponent>
。你的
addEvent
方法将变成这样:
addEvent() {
this.tableData.push({
lp: this.tableData.length + 1,
name: "name like...",
code: "1111",
color: "blue",
size: "S",
price: "99.99"
});
this.tableCarts.forEach(tableCart => tableCart.update());
//this.TableCart.update();
}
这是更新的PLUNKER演示的链接