Search code examples
angulartypescriptng-class

how do I use a variable for the value of ngClass?


I'm trying to make modals, so when I click each button different modals should show up, with different contents inside. On button click, active gets a value of true and when the active is true, modal div gets class .open.

HTML:

<button type="button" class="btn btn-4" (click)="myFunction(0)">ბანკი</button>
    <div class="modal"  [ngClass] = "**active[0].active1** ? 'open' : ''" >
      <div class="text">gfdgdgd</div>
      <button type="button" class="btn close" (click)="close()"><i class="fas fa-times-circle"></i></button>
    </div>

Typescript:

    active: any =  [
  {
    active1:false,
  },
  {
    active1:false,
  },
  {
    active1:false,
  },
  {
    active1:false,
  },
];
  constructor() { }
  


  ngOnInit(): void {
  }
  
 myFunction(id:any){
  this.active[id].active1 = true;
 }

 close(){
    this.active = false;
 }

It doesn't let me give ngClass value from active array. I have four modals, so each of them have different actives to have different contents. How can I manage to get ngClass = "active[0].active1 : 'open'", without errors? Also when I click button, it says 'Cannot set property 'active1' of undefined'?


Solution

  • If you want to manage an array of four booleans you do not need a nested dict, you can only to have:

    actives: boolean[] = [false, false, false, false];

    So, your class will simplify as:

    [ngClass] = "active[0] ? 'open' : ''"

    If you have the error 'Cannot set property 'active1' of undefined' means that is not defined when is render, you need to track the status of your vars when is render.