How do I handle a case in AngularJS 2 where on click of an element it needs to change its own style, and if other elements have that style they need to have it removed — prefera
The easiest fix to your problem is to assign a unique ID to each included element together with employing another variable to hold selected ID. The logic to turn on my-class
CSS class will now be based on the selected ID.
Your new HTML template:
> I'm a div that gets styled on click
Your toggleHighlight
function:
highlightedDiv: number;
toggleHighlight(newValue: number) {
if (this.highlightedDiv === newValue) {
this.highlightedDiv = 0;
}
else {
this.highlightedDiv = newValue;
}
}
Working Plnk: https://plnkr.co/edit/fNoXWhUhMaUoeMihbGYd?p=preview