Angular 2子组件从父组件数组中删除项目 [英] Angular 2 Child Component removing Item from Parent Component Array
问题描述
当前子组件试图删除父组件的数组时遇到问题.
Currently having issue with Child component trying to remove Parent component's Array.
父项:
@Component({
selector: 'parent',
templateUrl: 'app/templates/parent.html'
})
export class ParentComponent {
public items = [];
}
父HTML
<child [items]="items"></child>
<product *ngFor="let item of items><product>
子组件
@Component({
selector: 'child',
templateUrl: 'app/templates/child.html'
})
export class ChildComponent{
@Input() items;
emptyItems() {
this.items = [];
}
addItem() {
this.items.push({'title': 'foo'});
}
}
但是,当我调用emptyItems/addItem函数时,子视图中的items数组将反映更改,但是在父组件上它不会更改.
However when I call emptyItems/addItem function, the items array in the child view will reflect on changes, however on the parent component it doesnt change.
我需要使用输出吗?
推荐答案
正确的方法是使用 Output
但是,我们可以在您的项
上使用双向绑定,这将反映出双方的变化:
However we can use two-ways binding on your items
, this will reflect changes on both sides:
<child [(items)]="items"></child>
查看更多详细信息 https://angular.io/docs/ts/Latest/guide/cheatsheet.html
更新:尝试以不同的方式清空数组如何在JavaScript中清空数组?
Update: Try to empty you array differently How do I empty an array in JavaScript?
输出
应该可以运行 https://angular.io/docs/ts/latest/api/core/index/Output-var.html 这个想法是,您必须将更新的内容从 child 传递给 parent ,并手动更新 parent 的成员 items
Output
should work https://angular.io/docs/ts/latest/api/core/index/Output-var.html
The idea is that you have to pass updated things from child to parent and manually update member items
of the parent
这篇关于Angular 2子组件从父组件数组中删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!