我在循环中的ul中有很少的列表,当我单击任何列表时,当我单击其他列表时,它应该再次处于活动状态,上一个应该处于不活动状态,而当前应该再次处于活动状态,如选项卡,我尝试了活动但非活动状态无法正常工作,任何人都可以帮助我,这是代码
<ul>
<li *ngFor="let row of groups;let i = index" [ngClass]="{'active': row.isClicked}" (click)="row.isClicked = !row.isClicked">{{row.items}}</li>
</ul>
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"}]}]
}
答案 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;