How to change an element’s CSS class and remove all other classes on click
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:
<div (click)="toggleHighlight(1);" [ngClass]="{'my-class': highlightedDiv === 1}">
> I'm a div that gets styled on click
</div>
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
I have one hard solution to this problem:
<div (click)="onclick($event);" >
> I'm a div that gets styled on click
</div>
app:
class App {
constructor() {
}
onclick(event){
var l = event.target.parentElement.getElementsByClassName("my-class");
var count = l.length;
for(var i=0;i<count;i++){
l[i].className = "";
}
event.target.className = "my-class";
}
}
Plink: https://plnkr.co/edit/RHqL56GrTiV9olYE1Ars?p=preview
One solution which worked for me in showing the active menu is using typescript variable name in class as in
`class="{{ text1Class }}"`
and assign the class name in typescript.
`this.text1Class = "active";`
or
`this.text1Class = "inactive";`
You need to have different style class like this
`.inactive {
background-color : gray;
padding : 10px;
}
.active {
background-color : green;
padding : 10px;
}`
Assign the class name inside the function
`textOneClicked() : void {
this.text1Class = "active"; // set the active class
this.text2Class = this.text3Class = this.text4Class = "inactive"; // reset other classes
}`
A working Plunker here