0

Hi I have a component wrapped in a div that I want to change the class name of based on something like a button click. I have about 5 CSS classes that I want to be able to toggle the div class between using ng class. My questions how can I write ng class to use multiple Booleans for each class name?

julian reeves
  • 39
  • 1
  • 4
  • 1
    Does this answer your question? [Adding multiple class using ng-class](https://stackoverflow.com/questions/18871277/adding-multiple-class-using-ng-class) – D M Sep 02 '22 at 20:25

1 Answers1

0

HTML CODE

<div
  class="normal"
  [ngClass]="{
    green: selection.nature,
    blue: selection.sky,
    red: selection.love,
    yellow: selection.friendship
  }"
>
  <button (click)="select('nature')">NATURE</button>
  <button (click)="select('sky')">SKY</button>
  <button (click)="select('love')">LOVE</button>
  <button (click)="select('friendship')">FRIENDSHIP</button>
</div>

TS CODE

selection = {
    nature: false,
    sky: false,
    love: false,
    friendship: false,
  };
  select(value: string) {
    Object.keys(this.selection).forEach((k) => (this.selection[k] = false));
    this.selection[value] = true;
  }

I have created a stackblitz for the same if you want to check it in action. Please find it here

Please mark it as answer if it resolved your query. Happy Coding :)