Angular2从父组件更新嵌套组件中数据的方法 [英] Angular2 way to update data in nested component from parent component
问题描述
我有两个嵌套组件:grid-container
和grid-component
.
I have two nested components: grid-container
and grid-component
.
在grid-container
中,grid-component
初始化如下:
<grid [title]="'This is the grid title'" [data]="data"></grid>
数据已初始化.使用事件,可以在grid-container
中获取grid-component
中更新的data
.直到这里对我来说都是显而易见的.但是,我们通常应该在角度2中从容器组件(grid-container
)更新嵌套组件(在这种情况下为grid-component
)中的data
吗?
Data is initialized. Using events, the updated data
in grid-component
can be obtained in grid-container
. Its obvious until here for me. However, what should we typically do in angular 2 to update data
in the nested component (grid-component
in this case) from the container component (grid-container
)?
更具体地说,(或作为说明)我需要一个在容器组件(grid-container
)中添加项目的函数,该组件将在grid-component
More specifically, (or as an illustration) I need a function that adds an item in container component (grid-container
) which will be applied in data
in grid-component
ps: its not two-way data binding as in this question which also didn't work for this problem.
export class GridComponent{ //child component
@Input() data:any;
}
import { GridComponent } from 'somewhere';
export class GridContainer{ //parent component
data:any = [{/*an initialized object which is visible in child component*/}]
addItem(){
data.push({/*an item is added*/};
//PROBLEM IS THE NEWLY ADDED ITEM IS NOT VISIBLE IN GridComponent class.
}
}
推荐答案
有点晚了,但是也许有人到达这里会看到解决方案.我认为最好的解决方案是service
,它提供了简单而清晰的数据传递方法.在您的情况下,孩子应该subscribe
和observable
,并且在父组件中,无论何时要更新孩子组件中的数据,都应使用service方法传递数据.下面的例子.另请参阅角度2食谱
It's a bit late, but maybe if someone get here will see solution. I think the best solution for this is service
which provide easy and clear way to pass data. In your case the child's should subscribe
an observable
and in parent component you should use service method to pass data whenever you want to update data in child's components. Example below. Also look at the angular 2 cookbook
父组件
export class GridContainer {
constructor(private GridService: GridService) { }
private data: any[] = [];
private addItem(el) {
this.data.push(el);
this.GridService.pushGridData(this.data);
}
}
子组件
export class GridComponent implements OnInit, OnDestroy {
constructor(private GridService: GridService) { }
private data: any[] = [];
private subscribtion: Subscribtion;
ngOnInit(): void {
this.Subscribtion = this.GridService.gridData.subscribe(
(data) => { this.data = data; }
)
}
ngOnDestroy(): void {
this.Subscribtion.unsubscribe();
}
}
服务
@Injectable();
export class GridService {
constructor() { }
private gridDataSource = new Subject<any[]>()
gridData = this.gridDataSource.asObservable();
pushGridData(data) {
this.gridDataSource.next(data);
}
}
这篇关于Angular2从父组件更新嵌套组件中数据的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!