如何使用变量作为 ngClass 的值?

问题描述

我正在尝试制作模态,所以当我点击每个按钮时,应该显示不同的模态,里面有不同的内容。单击按钮时,active 的值为 true,当 active 为 true 时,模态 div 的类为 .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>

打字稿:

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


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

 close(){
    this.active = false;
 }

它不允许我从活动数组中给出 ngClass 值。我有四个模态,因此每个模态都有不同的活动以具有不同的内容。我如何设法获得 ngClass = "active[0].active1 : 'open'",而不会出错? 同样,当我单击按钮时,它会显示“无法设置未定义的属性 'active1'”?

解决方法

如果你想管理一个包含四个布尔值的数组,你不需要嵌套的字典,你只能拥有:

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

因此,您的类将简化为:

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

如果出现错误 'Cannot set property 'active1' of undefined' 表示未定义何时渲染,则需要在渲染时跟踪变量的状态。