Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add css class on selected list item

Tags:

angular

I have a list group and I want to add a css class when one item is selected using ngClass directive

how to verify is the item is selected?

I only have one option.. this is a sidebar component, and when I pick an option, it has to send it to the parent (I did that with @Output) and also have a css class on selected option...

this is my component.html

<ul class="list-group">
    <li *ngFor="let option of options" (click)="selectOption(option)" class="list-group-item" [ngClass]="option ? 'activate-class' : 'deactivate-class'">
        {{option.title}}
    </li>
</ul>

component.ts

  @Output() optionSelected: EventEmitter<any> = new EventEmitter();
  options = [
    {
        title: "Activate account",
        value: NavigationOptions.ACTIVATE_VENDOR
    },
    {
        title: "Deactivate account",
        value: NavigationOptions.DEACTIVATE_VENDOR
    }
];

  constructor() { }

  ngOnInit() {
  }

  selectOption(option) {
    this.optionSelected.emit(option);
  }
like image 606
user2004 Avatar asked Dec 06 '25 03:12

user2004


2 Answers

You could store the selected option in a variable and check for that:

public selectedOption;

selectOption(option) {
  this.optionSelected.emit(option);
  this.selectedOption = option;
}

and then check in the ngClass for this variable:

[ngClass]="option === selectedOption ? 'activate-class' : 'deactivate-class'"

or if you only want to set activate-class and don't need deactivate-class:

[class.activate-class]="option === selectedOption"
like image 106
Akora Avatar answered Dec 07 '25 17:12

Akora


There is no need to over-complicate things or bloat your ts file with code.

You can simply have a selectOption in the ts file.

TS :

selectOption; // If your option is an object, which it is - then consider adding an interface for it here    

There is also no need to have 'deactivate-class', if the class doesn't exist on it, we can assume it doesn't apply.

HTML :

<ul class="list-group">
  <li *ngFor="let option of options" (click)="selectOption = option" class="list-group-item" [ngClass]="{'activate-class' : selectOption === option}">
    {{option.title}}
  </li>
</ul>
like image 26
cmprogram Avatar answered Dec 07 '25 18:12

cmprogram



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!