Reputation: 335
I Have four values of products (A,B,C,D) (between a tag ). I create a child component angular and I want to pass a good value (A or B or Cor D) to parent component with EventEmitter.emit when user click but i doesn't can. I send always the first value A. This is my angular code
component.html
<table>
<thead>
<th><a #ca [attr.data-cat]="alax" (click)="getName(ca.dataset.cat)">A</a></th>
<th><a #ca [attr.data-cat]="beter" (click)="getName(ca.dataset.cat)">B</a></th>
<th><a #ca [attr.data-cat]="colar" (click)="getName(ca.dataset.cat)">C</a></th>
<th><a #ca [attr.data-cat]="dera" (click)="getName(ca.dataset.cat)">D</a></th>
</thead>
</table>
In component.ts
alax= 'ARMOIRS';
beter= 'PARASOLS';
colar= 'CAMBOUS';
dera= 'DIAMBRE';
@Output()
sendRequestData = new EventEmitter();
getName(catName:string) {
console.log("catName nom : "+catName);
this.sendRequestData.emit(catName);
}
In the father component.html I have :
<app-chilComponent (sendRequestData)="treatment($event)"></app-childComponent>
In father component.ts
treatment(message: any){
console.log(message) // I have always 'ARMOIRS' when I click on A or B or C or D
// I want to have 'ARMOIS' when I click on A and 'PARASOLS' when i click on B
}
Any idea ?
Upvotes: 0
Views: 781
Reputation: 31125
If you can adjust the data structure in the controller, I don't see the need for a template reference variable if you're only going to self reference it in an event handler.
You could achieve the same behavior with a minor change to the variables. Try the following
Controller
data = [
{ category: { name: 'ARMOIRS', value: 'alax' }, label: 'A' },
{ category: { name: 'PARASOLS', value: 'beter' }, label: 'B' },
{ category: { name: 'CAMBOUS', value: 'colar' }, label: 'C' },
{ category: { name: 'DIAMBRE', value: 'dera' }, label: 'D' },
];
getName(categoryName: string) {
console.log(categoryName);
this.sendRequestData.emit(catName);
}
Template
<table>
<thead>
<th *ngFor="let item of data">
<a (mouseup)="getName(item.category.name)">{{ item.label }}</a>
</th>
</thead>
</table>
Upvotes: 0
Reputation: 1247
You have used the same selector #ca
for all. Change them
<table>
<thead>
<th><a #ca1 [attr.data-cat]="alax" (click)="getName(ca1.dataset.cat)">A</a></th>
<th><a #ca2 [attr.data-cat]="beter" (click)="getName(ca2.dataset.cat)">B</a></th>
<th><a #ca3 [attr.data-cat]="colar" (click)="getName(ca3.dataset.cat)">C</a></th>
<th><a #ca4 [attr.data-cat]="dera" (click)="getName(ca4.dataset.cat)">D</a></th>
</thead>
</table>
Hope it helps!
Upvotes: 1