Rabie Daddi
Rabie Daddi

Reputation: 184

event binding between nested components

Supposing that I have two components compA and cmpB and cmpB used as child of cmpA (like select and option)

<div>
   <cmpA>
      <cmpB></cmpB>
      <cmpB></cmpB>
      <cmpB></cmpB>
   </cmpA>
</div>

how I can pass click event from cmpB to its parent by using ( ng-template and let-attr directive and ngTemplateOutlet ) I trid it but it didnt works reusable component in angular

because I have another solution but I wont use it bcs its not practical

I will mention it just to understand what I mean

<div>
   <cmpA #cmpA1>
      <cmpB (click)="cmp1.fn()"></cmpB>
      <cmpB (click)="cmp1.fn()"></cmpB>
      <cmpB (click)="cmp1.fn()"></cmpB>
   </cmpA>
</div>
<div>
   <cmpA #cmpA2>
      <cmpB (click)="cmp2.fn()"></cmpB>
      <cmpB (click)="cmp2.fn()"></cmpB>
      <cmpB (click)="cmp2.fn()"></cmpB>
   </cmpA>
</div>

I want all of that to be "under the hood"

Upvotes: 0

Views: 306

Answers (1)

amakhrov
amakhrov

Reputation: 3939

The idea is that cmpA and cmpB should be aware of each other. In cmpB you can inject cmpA, and then call its methods directly. And the other way round, cmpA can get all child cmpB items via @ContentChildren decorator and do smth with them directly (e.g. update their "checked" state).

Angular Material is a good learning source. E.g. you could look at how MatRadioGroup interacts with its nested MatRadioButtons: https://github.com/angular/components/blob/master/src/material/radio/radio.ts#L487

Upvotes: 1

Related Questions