与组件之间的角度数据通信

时间:2017-09-06 11:49:34

标签: angular typescript primeng primeng-datatable

我有一个父组件(P1)和两个子组件(C1和C2)。 两个子组件都有一个可编辑的primeng数据表。 我在P1上有两个按钮: fetch()和save() fetch()调用数据库来获取数据。 我正在使用共享服务来获取数据并使用BehaviorSubject将其传递给组件。 我的数据对象如下:

export interface ParentObj { name: string; child1 : Child1[]; child2: Child2[]}
export interface Child1 { weight: number;}
export interface Child2 { code: string;}

子组件从共享服务订阅数据。 现在问题是Child组件也修改了他们拥有的数据。 所以点击P1上的 save(),我无法从子组件中获取最新的修改值,因为我没有办法通知P1 C1和/或C2已经改变了数据

有没有办法完成同样的操作,这样我可以在调用 save()时通知子组件,并且它反映在 ParentObj ?中。

2 个答案:

答案 0 :(得分:1)

我能够使用ViewChild中的'@angular/core'来解决它,因为子组件上没有事件触发器。 父级可以使用@ViewChild(ChildComponent) child;读取子属性 参考:Here

答案 1 :(得分:0)

您可以将事件发射器用于此目的,这在从子组件与父组件进行通信时非常有用。

实施例: -

P1组件: -

<c1 (notifyParent)="notify(data)"></c1>
<c2 (notifyParent)="notify(data)"></c1>

notify(data) {
    console.log(data); //notify parent
}

C1组件: -

@Output() notifyParent= new EventEmitter();

然后

this.notifyParent.emit(data) //or notify with true value

C2组件: -

@Output() notifyParent= new EventEmitter();

然后

this.notifParent.emit(data) //or notify with true value