Home > other >  How to do add active class on click in angular?
How to do add active class on click in angular?

Time:10-31

I want to change active class in li click

<pre> <li  (click)="useLanguage('fr')"></li>
                    <li  (click)="useLanguage('zh')"></li>
                    <li  (click)="useLanguage('en')"></li>

In component I have written the function

useLanguage(language: string) {
    this.translate.use(language);
}

I want to add the active class when click on li also have to removed from other li. How to do?

CodePudding user response:

A class can be conditionally applied using this syntax:

<div [class.className]="someBoolean"><div>

So, if you store the selected language in a variable, you can do like this:

Template:

  <li [class.active]="selectedLanguage==='fr'" (click)="useLanguage('fr')"></li>
  <li [class.active]="selectedLanguage==='zh'" (click)="useLanguage('zh')"></li>
  <li [class.active]="selectedLanguage==='en'" (click)="useLanguage('en')"></li>

Component:

selectedLanguage = 'fr';

useLanguage(language: string) {
    this.translate.use(language);
    this.selectedLanguage = language;
}

Here's a working StackBlitz demo.

CodePudding user response:

// default lang

selectedLanguage = "fr";

// html

<li [ngClass]="{'selected-value' : selectedLanguage==='fr'}"(click)="useLanguage('fr')"></li>

// change language function

useLanguage(language: string) {
    this.translate.use(language);
    this.selectedLanguage = language;
} 
  • Related