2017-09-06 75 views
1

我有一个父组件(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;} 

子组件订阅从共享服务的数据。 现在的问题是,子组件也会修改它们拥有的数据。 因此,在P1上点击保存(),我无法从子组件获取最新的修改值,因为我没有任何方式通知P1 C1和/或C2已更改数据。

有没有办法来完成相同的,这样我可以通知子组件时保存()被调用,它在ParentObj体现?

+0

检查了这一点:https://stackoverflow.com/a/44455401/5346095 –

+0

@Manu:数据已经从父母传给孩子,但不其他方式,因为没有像Child组件上的事件那样的通信方式。 – Amit

+0

你应该尝试使用来自RxJS库的行为主题 –

回答

0

我能够使用ViewChild'@angular/core'来解决这个问题,因为是在子组件没有事件触发。 家长可以读取子节点属性使用@ViewChild(ChildComponent) child; 参考:Here

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