How to call router outlet child component method from parent comonent

前端 未结 10 1979
甜味超标
甜味超标 2020-12-18 19:42

I am new to angular2


    

I have a button in parent component, if

10条回答
  •  借酒劲吻你
    2020-12-18 20:00

    I think Event emitter can do the trick for you

    Though you can use it directly in child component also but using a common service here would be a good practice

    First you need to create an emitter in a service something like

    export class EmitterService {
       public nameEmitter:EventEmitter=new EventEmitter(); 
    
        //method to get question
        changeName(name:string){   
            this.nameEmitter.emit(name)    
        }
    
    }
    

    Then in root component inject service dependency and call change name method to emit the change

     constructor(private emitter :EmitterService) {}
     this.emitter.changeName("New Name");
    

    And at the end in child component subscribe to changes

    this.emitter.nameEmitter.subscribe(name=>{this.name=name})
    

    Here is working plunker

提交回复
热议问题