Angular 与组件之间的数据通信
Angular data communication to and from components
我有一个父组件 (P1) 和两个子组件(C1 和 C2)。
两个子组件都有一个 primeng data-table,它是 editable。
我在 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 上单击 save() 时,我无法从子组件获取最新的修改值,因为我没有任何方式通知 P1 C1 and/or C2修改了数据
有没有一种方法可以实现相同的目的,以便在 save() 被调用时通知子组件并且它反映在 ParentObj?.
您可以为此目的使用事件发射器,这在子组件与父组件通信时最有用。
示例:-
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
我能够使用 '@angular/core'
中的 ViewChild
解决它,因为 child 组件上没有事件触发器。
parent 可以使用 @ViewChild(ChildComponent) child;
读取 child 属性
参考:Here
我有一个父组件 (P1) 和两个子组件(C1 和 C2)。 两个子组件都有一个 primeng data-table,它是 editable。 我在 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 上单击 save() 时,我无法从子组件获取最新的修改值,因为我没有任何方式通知 P1 C1 and/or C2修改了数据
有没有一种方法可以实现相同的目的,以便在 save() 被调用时通知子组件并且它反映在 ParentObj?.
您可以为此目的使用事件发射器,这在子组件与父组件通信时最有用。
示例:-
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
我能够使用 '@angular/core'
中的 ViewChild
解决它,因为 child 组件上没有事件触发器。
parent 可以使用 @ViewChild(ChildComponent) child;
读取 child 属性
参考:Here