Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angular

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?

like image 718
None Avatar asked Mar 09 '23 16:03

None


1 Answers

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>();

}
like image 97
Poul Kruijt Avatar answered Mar 23 '23 22:03

Poul Kruijt