Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change an element’s CSS class and remove all other classes on click

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 — preferably in one function.

Similar to Angular.js How to change an elements css class on click and to remove all others, only in AngularJS 2, using TypeScript.

Component

https://plnkr.co/edit/Q2BoU4sNnXdaJB5vrZ8h?p=preview

//our root app component
import { NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {Component} from '@angular/core';

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <div (click)="isClassVisible = !isClassVisible;" [ngClass]="{'my-class': isClassVisible }">
        > I'm a div that gets styled on click
      </div>
      <div (click)="isClassVisible = !isClassVisible;" [ngClass]="{'my-class': isClassVisible }">
        > I also want to be styled but only when Im clicked
      </div>
      <div (click)="isClassVisible = !isClassVisible;" [ngClass]="{'my-class': isClassVisible }">
        > When one of us gets clicked the we want to be the only one with the style all others go back to normal
      </div>
       <div (click)="isClassVisible = !isClassVisible;" [ngClass]="{'my-class': isClassVisible }">
        > I'm just here cause my creator likes even numbers
      </div>
    </div>
  `,
  styles: [
  `
  .my-class {
    background-color: yellow;
  }
  `
  ]
})
class App {
  isClassVisible: false;

  constructor() {
  }

}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}
like image 575
BlunderCode Avatar asked Nov 23 '16 00:11

BlunderCode


1 Answers

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

like image 83
Ranjith Bhaskaran Avatar answered Oct 24 '22 16:10

Ranjith Bhaskaran