Child listens for parent event in Angular 2

前端 未结 4 1178
轮回少年
轮回少年 2020-12-07 16:10

In angular docs there is a topic about listening for child events from parents. That\'s fine. But my purpose is something reverse!. In my app there is an \'admin.component\'

4条回答
  •  广开言路
    2020-12-07 16:56

    For the sake of posterity, just thought I'd mention the more conventional solution to this: Simply obtain a reference to the ViewChild then call one of its methods directly.

    @Component({
      selector: 'app-child'
    })
    export class ChildComponent {
    
      notifyMe() {
        console.log('Event Fired');
      }
    }
    
    @Component({
      selector: 'app-parent',
      template: ``
    })
    export class ParentComponent {
    
      @ViewChild('child')
      private child: ChildComponent;
    
      ngOnInit() {
        this.child.notifyMe();
      }
    }
    

提交回复
热议问题