首页 > 解决方案 > 如何使用变量作为 ngClass 的值?

问题描述

我正在尝试制作模态,所以当我单击每个按钮时,应该显示不同的模态,其中包含不同的内容。单击按钮时,active 的值为 true ,当 active 为 true 时,模态 div 的值为 class .open

HTML:

<button type="button" class="btn btn-4" (click)="myFunction(0)">ბანკი&lt;/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,
  },
  {
    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'”?

标签: angulartypescriptng-class

解决方案


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

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

因此,您的课程将简化为:

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

如果您有错误'Cannot set property 'active1' of undefined'意味着在渲染时未定义,您需要在渲染时跟踪您的 vars 的状态。


推荐阅读