None
None

Reputation: 9247

How to call method from parent when i click on child?

I have two components, parent and child. In child i have button. I want when user click on that button in child to call method that is in parent. Any suggestion?

Upvotes: 4

Views: 1440

Answers (1)

Poul Kruijt
Poul Kruijt

Reputation: 71891

This is very basic angular, and you will find plenty of examples through the guides on https://angular.io.

But if you still could not find it, you have to use the @Output decorator, set an EventEmitter field to it and call emit when the button is clicked. This way you can attach to it from your parent using the event notation ():

parent

@Component({
   selector: 'parent',
   template: `<child (buttonClick)="onButtonClick($event)"></child>`
})
export class ParentComponent {

   public onButtonClick(event: MouseEvent): void {
      // ...
   }

}

child

@Component({
    selector: 'child',
    template: `<button (click)="buttonClick.emit($event)"></button>`
})
export class ChildComponent {

   @Output()
   public buttonClick: EventEmitter<MouseEvent> = new EventEmitter<MouseEvent>();

}

Upvotes: 7

Related Questions