1

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.

1
  • 1
    Did you try with Output() decorator? Commented Nov 24, 2020 at 15:15

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks!! lissettdm its working exactly what i wanted, just one thing want to ask how to define exact click event type in EventEmitter<any> instead of <any>. and i believe this the right way to pass parent event o child what you have corrected instead the above one suggest by Pankaj please suggest.
lissettdm can you please suggest me any network where i can directly ask question to you for better & quick response if i am not able to found here in time.
For example EventEmitter<number>, is related to the data type you will send on event emit, this.listenParentHandler.emit(1000).
1

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.

Forked Stackblitz

2 Comments

Thanks for answer but i want to pass data using appropriate Input or Output Decorators & also current one Forked Stackblitz is not working.
@Roy I'm sorry, update the link. And added link to Host decorator documentation. Can you please check update one?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.