How do I call a method from the parent when the child is clicked?
I have two components: parent and child. Child I have a button. I want when the user clicks this button in the child method to call which is in the parent. Any suggestion?
+3
None
source
to share
1 answer
It is very simple angular and you will find many examples through the tutorials at https://angular.io .
But if you still can't find it, you should use a decorator @Output
, set a field for it EventEmitter
and call emit
on button click. This way you can attach your parent to it using 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>();
}
+6
PierreDuc
source
to share