Parent-Component
public inputToChild: Object;
Parent-HTML
<child [data]="inputToChild"> </child>
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.
}
SharedService
subject: Subject<Object>;
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.})
4 回答
使用RxJs,您可以在父组件中声明Subject并将其作为Observable传递给子组件,子组件只需要订阅此Observable .
Parent-Component
Parent-HTML
Child-Component
据我所知,有两种标准方法可以做到这一点 .
1. @Input
只要父项中的数据发生更改,子项就会在ngOnChanges方法中得到通知 . 孩子可以采取行动 . 这是与孩子互动的标准方式 .
在共享服务中创建服务并使用observable . 孩子订阅它,每当有变化时,孩子都会收到通知 . 这也是一种流行的方法 . 如果要发送除传递的数据以外的其他内容作为输入,可以使用此功能 .
在子组件中使用@Input()装饰器以允许父级绑定到此输入 .
在子组件中,您按原样声明它:
@Input() myInputName: myType
要将属性从父级绑定到子级,必须在模板中添加装订括号和它们之间的输入名称 .
示例:
<my-child-component [myChildInputName]="myParentVar"></my-child-component>
但要注意,对象作为引用传递,因此如果在子对象中更新了对象,则父对象的var将会更新 . 这可能会导致某些不需要的行为 . 对于主要类型,将复制值 .
进一步阅读:
文件:https://angular.io/docs/ts/latest/cookbook/component-communication.html
在父级中,您可以使用@ViewChild引用子级 . 在需要时(即事件将被触发),您可以使用@ViewChild引用从父级执行子方法 .