Angular 与组件之间的角度数据通信
我有一个父组件(P1)和两个子组件(C1和C2)。 两个子组件都有一个可编辑的预处理数据表。 P1上有两个按钮:fetch()和save()。 fetch()调用数据库以获取数据。 我使用共享服务获取数据,并使用BehaviorSubject将其传递给组件。 我的数据对象看起来像:Angular 与组件之间的角度数据通信,angular,typescript,primeng,primeng-datatable,Angular,Typescript,Primeng,Primeng Datatable,我有一个父组件(P1)和两个子组件(C1和C2)。 两个子组件都有一个可编辑的预处理数据表。 P1上有两个按钮:fetch()和save()。 fetch()调用数据库以获取数据。 我使用共享服务获取数据,并使用BehaviorSubject将其传递给组件。 我的数据对象看起来像: export interface ParentObj { name: string; child1 : Child1[]; child2: Child2[]} export interface Child1 { we
export interface ParentObj { name: string; child1 : Child1[]; child2: Child2[]}
export interface Child1 { weight: number;}
export interface Child2 { code: string;}
子组件从共享服务订阅数据。
现在的问题是子组件也修改了它们拥有的数据。
因此,在P1上单击save(),我无法从子组件获取最新修改的值,因为我无法通知P1 C1和/或C2已更改数据
有没有办法做到这一点,以便我可以在调用save()时通知子组件,它会反映在ParentObj中?您可以使用事件发射器实现此目的,这在子组件与父组件通信时非常有用 例如:- P1组件:-
<c1 (notifyParent)="notify(data)"></c1>
<c2 (notifyParent)="notify(data)"></c1>
notify(data) {
console.log(data); //notify parent
}
@Output() notifyParent= new EventEmitter();
@Output() notifyParent= new EventEmitter();
然后
this.notifyParent.emit(data) //or notify with true value
this.notifParent.emit(data) //or notify with true value
C2组件:-
<c1 (notifyParent)="notify(data)"></c1>
<c2 (notifyParent)="notify(data)"></c1>
notify(data) {
console.log(data); //notify parent
}
@Output() notifyParent= new EventEmitter();
@Output() notifyParent= new EventEmitter();
然后
this.notifyParent.emit(data) //or notify with true value
this.notifParent.emit(data) //or notify with true value
我能够使用
“@angular/core”
中的ViewChild
解决这个问题,因为子组件上没有事件触发器。
父级可以使用@ViewChild(ChildComponent)子级读取子属性代码>
参考资料:请检查:@Manu:数据已经从父级传递到子级,但不是相反,因为没有像子组件上的事件那样的通信方式。您应该尝试使用RxJS Library中的行为主题尝试使用reduxngrx store
进行状态管理和跨组件共享数据。