Reputation: 877
I have a parent component and in that component, 1 other component is included multiple times.
Structure :
parent component :
<table>
<tr class="">
<td>buttons</td>
</tr>
<tr app-myComp></tr>
<tr app-myComp></tr>
<tr app-myComp></tr>
<tr app-myComp></tr>
</table>
Child (myComp) component :
@Component({
selector: 'tr[app-myComp]',
template: `
<td><button [style.color]="myColor" (click)="changeColor()">changeColor</button></td>
`
})
export class MyComponent {
myColor: string = "blue";
changeColor(): void{
this.myColor = "red"
}
}
When I click on button , text color of button changes from blue to red.
But my question is how can I change text color of only clicked button to red and reset all other button's text color to blue?
I know I can get list of MyComponent by @ViewChildren but how can I use them to reset button's text color to blue except clicked one.
I am using angular 4.3.4
codepen link : Angular 4 app
Upvotes: 0
Views: 1087
Reputation: 28738
You would need to add a property on the parent component with assigned value to the index of the clicked child. Change its value each time the child is clicked and pass it as a boolean @Input to the child (true if the the property value equal to child's index, false, well, in the reverse condition). In the child component add a condition to check that @Input and set the color only on that condition. And for the child index tracking, add *ngFor instead of repeating the hard coded multiple <tr app-myComp>
.
child class:
...
myColor: string;
@Input()
set chosen(chosen: boolean) {
this.myColor = chosen ? "red" : "blue"
}
...
parent view:
<table>
<tr class="">
<td>buttons</td>
</tr>
<tr app-myComp (click)="chosenTr = i" [chosen]="i == chosenTr" *ngFor="let item of [1,2,3,4]; let i = index"></tr>
</table>
parent class:
...
chosenTr = -1;
...
Upvotes: 1