angular add ngClass by click event

Published

I have the following html:

<label (click)="setRole('All')" class="btn btn-cb-bordered" [class.active]="isChecked(roles, 'All')"><input type="checkbox" name="roles" value="All">All</label>
<label (click)="setRole('A')" class="btn btn-cb-bordered" [class.active]="isChecked(roles, 'A')"><input type="checkbox" name="roles" value="A">A</label>
<label (click)="setRole('B')" class="btn btn-cb-bordered" [class.active]="isChecked(roles, 'B')"><input type="checkbox" name="roles" value="B">B</label>

.ts:

public roles = [];

public setRole(role: string): void {
  if (this.roles.indexOf(role) == -1) {
    this.roles.push(role);
  } else {
    this.roles = this.roles.filter(item => item != role);
  }
}

public isChecked(val1: any, val2: any): any {
  return (val1.filter(item => item == val2)).length > 0;
}

But for some reasons it works if I click on item 2 times.
How can I get it working?

Source: Angular Questions

Published
Categorized as angular Tagged

Answers

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq