据我所知,有两种标准方法可以做到这一点 .
1. @Input
只要父项中的数据发生更改,子项就会在ngOnChanges方法中得到通知 . 孩子可以采取行动 . 这是与孩子互动的标准方式 .
Parent-Component
public inputToChild: Object;
Parent-HTML
Child-Component: @Input() data;
ngOnChanges(changes: SimpleChanges){
// Whenever the data in the parent changes, this method gets triggered. You
can act on the changes here. You will have both the previous value and the
current value here.
}
Shared service concept
在共享服务中创建服务并使用observable . 孩子订阅它,每当有变化时,孩子都会收到通知 . 这也是一种流行的方法 . 如果要发送除传递的数据以外的其他内容作为输入,可以使用此功能 .
SharedService
subject: Subject;
Parent-Component
constructor(sharedService: SharedService)
this.sharedService.subject.next(data);
Child-Component
constructor(sharedService: SharedService)
this.sharedService.subject.subscribe((data)=>{
// Whenever the parent emits using the next method, you can receive the data
in here and act on it.})