如何将动态类添加到 angular 中的循环元素 [英] How to add dynamic classes to looped elements in angular

查看:29
本文介绍了如何将动态类添加到 angular 中的循环元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个循环列表.单击任何块时,我必须添加类 active.我不确定如何使用 [ngClass] 做到这一点.请帮帮我.

这是HTML代码:

<div class="list-header"><label>{{ cell.name }}</label>

<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>

我的 TS 代码:

myData = [{'name': 'abc','array': ["assass","From Mac","New", "test 1", "test 10", "test 2", "test 3", "test 4", "test 5", "test6"、测试 7"、测试 8"、测试 9"]},{'name': '所有类型和选项','array': ['Camera','del TYPE','Fan','hardware','icons','mobile','new asset type']},{'name': '我是猫','array': ['am type','camera','new 423423']},{'name': '没有资产类型的猫,已添加 dec','阵列':['相机']},{'name': '具有一种资产类型的猫','阵列':['相机']},{'name': '颜色','阵列':['粉红色','黄色']}];

解决方案

模板:

<div class="list-header"><label>{{ cell.name }}</label>

<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>

I have a looped list. I have to add class active when any block is clicked. I am not sure how to do it using [ngClass]. Please help me.

It is HTML code:

<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>

my TS code:

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']
}
];

解决方案

template:

<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>

这篇关于如何将动态类添加到 angular 中的循环元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆