首页 文章

如何从父级到子级以角度发出事件?

提问于
浏览
26

我目前正在使用angular2 . 通常我们使用@Output()addTab = new EventEmitter();然后addTab.emit()向父组件发出一个事件 . 从父母到孩子,我们有什么方法可以做副诽谤 .

4 回答

  • 36

    使用RxJs,您可以在父组件中声明Subject并将其作为Observable传递给子组件,子组件只需要订阅此Observable .

    Parent-Component

    private eventsSubject: Subject<void> = new Subject<void>();
    
    emitEventToChild() {
      this.eventsSubject.next()
    }
    

    Parent-HTML

    <child [events]="eventsSubject.asObservable()"> </child>
    

    Child-Component

    private eventsSubscription: any
    
    @Input() events: Observable<void>;
    
    ngOnInit(){
      this.eventsSubscription = this.events.subscribe(() => doSomething())
    }
    
    ngOnDestroy() {
      this.eventsSubscription.unsubscribe()
    }
    
  • 1

    据我所知,有两种标准方法可以做到这一点 .

    1. @Input

    只要父项中的数据发生更改,子项就会在ngOnChanges方法中得到通知 . 孩子可以采取行动 . 这是与孩子互动的标准方式 .

    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.
    }
    
    • Shared service concept

    在共享服务中创建服务并使用observable . 孩子订阅它,每当有变化时,孩子都会收到通知 . 这也是一种流行的方法 . 如果要发送除传递的数据以外的其他内容作为输入,可以使用此功能 .

    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.})
    
  • 34

    在子组件中使用@Input()装饰器以允许父级绑定到此输入 .

    在子组件中,您按原样声明它:

    @Input() myInputName: myType

    要将属性从父级绑定到子级,必须在模板中添加装订括号和它们之间的输入名称 .

    示例:

    <my-child-component [myChildInputName]="myParentVar"></my-child-component>

    但要注意,对象作为引用传递,因此如果在子对象中更新了对象,则父对象的var将会更新 . 这可能会导致某些不需要的行为 . 对于主要类型,将复制值 .

    进一步阅读:

    文件:https://angular.io/docs/ts/latest/cookbook/component-communication.html

  • 6

    在父级中,您可以使用@ViewChild引用子级 . 在需要时(即事件将被触发),您可以使用@ViewChild引用从父级执行子方法 .

相关问题