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);
}
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"
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With