Burak
Burak

Reputation: 5764

Angular 4 - How to call parent method from child component without EventEmitter?

I have following hierarchy in my app:

AppComponent » ThemeComponent » HeaderNavComponent

The ThemeComponent has a method

   qrIconClicked(){

   }

I need to call this method from HeaderNavComponent.

How can I do that?

Upvotes: 3

Views: 5438

Answers (1)

Aniruddha Das
Aniruddha Das

Reputation: 21698

You can do that by defining @Output type variable in your child HeaderNavComponent component and bubble and event when you want from the child which will be captured by the parent component ThemeComponent and fire a method qrIconClicked()

So your child component will look like

export class HeaderNavComponent {
   @Output() editDone = new EventEmitter<EditEvent>();

  onSubmit() {
    if (some condition) {
      this.editDone.emit('some value');
    } else {
      this.editDone.emit('other value');
    }
  }
}

As you raise editDone event from your child component, while calling your child component you can assign a function to call when that event will be emmitted.

<header-nav(editDone)="qrIconClicked($event)"><header-nav>

And finally you function will get value from child in the event passed to parent

   qrIconClicked(event: any){
     //event will hold value from chilld 
   }

Upvotes: 3

Related Questions