How can i use or pass parent click handler to child component in angular? I have use @input decorator to bind parent data for my child component but then parent gets failed to listen of own click events. this stackblitz is the live code i am using please correct it.
2 Answers
Use the Output decorator:
child.component.js
export class ChildComponent implements OnInit {
@Output() listenParentHandler : EventEmitter<any> = new EventEmitter();
childClick(){
this.listenParentHandler.emit();
}
}
parent.component.html
<app-child (listenParentHandler)="buttonClick()"></app-child>
See: https://stackblitz.com/edit/angular-ivy-bswpaj?file=src%2Fapp%2Fparent%2Fchild%2Fchild.component.ts
3 Comments
If the parent and child component has tight coupling between each other. For example tab-group and tab component
<tab-group>
<tab title="Tab 1">Tab 1</tab>
<tab title="Tab 1">Tab 2</tab>
<tab title="Tab 2">Tab 3</tab>
</tab-group>
In such cases you can use @Host decorator to get an access of parent component instance inside ChildComponent. But when you use Host decorator it says adds tight coupling between two components.
constructor(
@Host() private parent: ParentComponent
) {}
Though you can use @Optional decorator incase you don't want to use it with ParentComponent, but again it's not appropriate way to use @Optional() with Host decorator.
2 Comments
Host decorator documentation. Can you please check update one?