【问题标题】:How to add dynamic classes to looped elements in angular如何以角度向循环元素添加动态类
【发布时间】:2019-07-01 05:27:52
【问题描述】:

我有一个循环列表。单击任何块时,我必须添加类active。我不知道如何使用[ngClass]。请帮帮我。

是HTML代码:

<div *ngFor="let cell of myData">
    <div class="list-header">
        <label>{{ cell.name }}</label>
    </div>
    <div class="list-group">
        <a class="list-group-item list-group-item-action d-flex" *ngFor="let unit of cell.array" (click)= "onClick()" [ngClass]="{'active': this.active}">
            <label>{{ unit }}</label>
        </a>
    </div>
</div>

我的 TS 代码:

myData = [
{
  'name': 'abc',
  'array': ["asass","From Mac","New", "test 1", "test 10", "test 2", "test 3", "test 4", "test 5", "test 6", "test 7", "test 8", "test 9" ]
},
{
  'name': 'all types and options',
  'array': ['Camera','del TYPE','Fan','hardware','icons','mobile','new asset type']
},
{
  'name': 'am cat',
  'array': ['am type','camera','new 423423']
},
{
  'name': 'cat with no asset types, dec added',
  'array': ['camera']
},
{
  'name': 'cat with one asset type',
  'array': ['camera']
},
{
  'name': 'colors',
  'array': ['pink', 'yellow']
}
];

【问题讨论】:

    标签: angular7 ngfor


    【解决方案1】:
    <div class="my_class" (click)="clickEvent()"  
        [ngClass]="active ? 'success' : 'danger'">                
         Some content
    </div>
    
    active: boolean = false;
    clickEvent(){
        this.active = !this.active;       
    }
    

    【讨论】:

    • 它不起作用,因为它会为每个元素添加活动类。我想为那些被点击的元素添加活动类。
    • 你必须根据需要修改它
    • 我已根据需要对其进行了修改。但是当 active 变为 true 时,它​​会影响循环中的每个元素。我们可以像使用索引一样为单个元素制作它吗?
    • 是的,兄弟,它做得很好......谢谢。
    【解决方案2】:

    模板:

    <div *ngFor="let cell of myData">
          <div class="list-header">
            <label>{{ cell.name }}</label>
          </div>
          <div class="list-group">
            <a class="list-group-item list-group-item-action d-flex" *ngFor="let unit of cell.array; let i = index" (click)= "cell.selectedIndex=i" [ngClass]= "{ 'active': cell.selectedIndex === i }" >
              <label>{{ unit }}</label>
            </a>
          </div>
        </div>
    

    【讨论】:

      猜你喜欢
      • 2017-11-08
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 2022-07-29
      • 2015-05-18
      • 1970-01-01
      • 2021-08-21
      • 2014-09-30
      相关资源
      最近更新 更多