Emit event through nested components in Angular2

前端 未结 3 819
猫巷女王i
猫巷女王i 2021-01-04 14:09

One can use Output() decorator to emit the event from the child component so that the parent component can catch it. What I need is to catch an event emitted by

3条回答
  •  青春惊慌失措
    2021-01-04 14:33

    the thierry answer is the correct aproach, but if you want to avoid use shared service, you can do somthing like this

    view.html

    
    
    

    view.ts

    actionHandler(event){
      //doSomething
    }
    

    componentA.html

    
    
    

    componentA.ts

    @Output() actionA: EventEmitter<{}> = new EventEmitter();
    
    constructor() {
    }
    
    actionHandlerA(event){
      this.actionA.emit(event);
    }
    

    componentB.html

    click me
    

    componentB.ts

    @Output() actionB: EventEmitter<{}> = new EventEmitter();
    
    constructor() {
    }
    
    actionHandlerB(o: objectModel){
      this.actionB.emit(new objectModel(o));
    }
    

提交回复
热议问题