如何在Angular7中使用循环使列表活动和不活动的onclick数据

时间:2019-09-12 18:31:26

标签: html angular

我在循环中的ul中有很少的列表,当我单击任何列表时,当我单击其他列表时,它应该再次处于活动状态,上一个应该处于不活动状态,而当前应该再次处于活动状态,如选项卡,我尝试了活动但非活动状态无法正常工作,任何人都可以帮助我,这是代码

app.component.html

<ul>
  <li  *ngFor="let row of groups;let i = index" [ngClass]="{'active': row.isClicked}" (click)="row.isClicked = !row.isClicked">{{row.items}}</li>
  </ul>

app.component.ts

import { Component,ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent  {
groups = [{"id":1,"name":"pencils","items":"red pencil","Status":[{"id":1,"name":"green"},{"id":2,"name":"red"},{"id":3,"name":"yellow"}],"loc":[{"id":1,"name":"loc 1"},{"id":2,"name":"loc 2"},{"id":3,"name":"loc 3"}]},{"id":2,"name":"rubbers","items":"big rubber","Status":[{"name":"green"},{"name":"red"}],"loc":[{"name":"loc 2"},{"name":"loc 3"}]},{"id":3,"name":"rubbers1","items":"big rubber1","Status":[{"name":"green"},{"name":"red"}],"loc":[{"name":"loc 2"},{"name":"loc 3"}]}]
}

2 个答案:

答案 0 :(得分:1)

尝试这样:

<ul>
  <li *ngFor="let row of groups;let i = index" [ngClass]="{'active': clickedIndex == i}" (click)="clickedIndex == i? clickedIndex = null : clickedIndex = i">
     {{row.items}}
  </li>
</ul>

clickedIndex保留单击的li的索引。仅当clickedIndex是该li的索引时,才应用“活动”类。如果您再次单击活动的li,则clickedIndex会更改为null,以使其不再活动

请参见Demo

答案 1 :(得分:0)

您应该遍历列表中的所有条目,并在其上设置row.isClicked = false

将处理程序(click)="row.isClicked = !row.isClicked"移动到组件并进行增强 像这样:

this.rows.forEach(row => row.isClicked = false);
selectedRow.isClicked = !selectedRow.isClicked;