我有一个结构像:
<div>
<ul>
<li>
<ul>
<li>Option 1</li>
<li>Option 2</li>
<li>Option 3</li>
</ul>
</li>
<li>
<ul>
<li>Option 1</li>
<li>Option 2</li>
<li>Option 3</li>
</ul>
</li>
<li>
<ul>
<li>Option 1</li>
<li>Option 2</li>
<li>Option 3</li>
</ul>
</li>
<ul>
</div>
我需要在元素上添加class active,而不是单击兄弟姐妹。 我正在使用
public select(item) {
this.selectedLi = item;
}
public isActive(item) {
return this.selectedLi === item;
}
但是这会增加所有李的课程而不是当前的。
有没有办法做到这一点。请帮助。
答案 0 :(得分:0)
你可以试试这样的事情
<div>
<ul>
<li>
<ul>
<li [class.active]="selectedLi=='o1'" (click)="select('o1')">Option 1</li>
<li [class.active]="selectedLi=='o2'" (click)="select('o2')">Option 2</li>
<li [class.active]="selectedLi=='o3'" (click)="select('o3')">Option 3</li>
</ul>
......
</li>
</ul>
</div>
select(option:string){
this.selectedLi=option;
}
这只会在点击时在你想要的li元素上添加活动类。
答案 1 :(得分:0)
您可以使用[ngClass]
设置课程,然后在component
this.selectedItem = newValue;
中设置该值selected
<强> HTML 强>
<div>
<ul>
<li>
<ul>
<li [ngClass]="{'active': selectedItem.firstLi == 2}" (click)="listClick($event, 2, 'firstLi')">Option 1</li>
<li [ngClass]="{'active': selectedItem.firstLi == 3}" (click)="listClick($event, 3, 'firstLi')">Option 2</li>
<li [ngClass]="{'active': selectedItem.firstLi == 4}" (click)="listClick($event, 4, 'firstLi')">Option 3</li>
</ul>
</li>
<li>
<ul>
<li [ngClass]="{'active': selectedItem.secondLi == 6}" (click)="listClick($event, 6, 'secondLi')">Option 1</li>
<li [ngClass]="{'active': selectedItem.secondLi == 7}" (click)="listClick($event, 7, 'secondLi')">Option 2</li>
<li [ngClass]="{'active': selectedItem.secondLi == 8}" (click)="listClick($event, 8, 'secondLi')"> Option 3</li>
</ul>
</li>
</ul>
</div>
<强>组件:强>
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
selectedItem = {
firstLi: '',
secondLi: ''
}
listClick(event, newValue, value) {
console.log(newValue);
this.selectedItem[value] = newValue; // don't forget to update the model here
// ... do other stuff here ...
}
}
答案 2 :(得分:0)
You can use [class] property with conditional operator to set class,like below
<div>
<ul>
<li>
<ul>
<li [class]="(isActive('o1') === true )? ' active' : ''" (click)="select('o1')">Option 1</li>
<li [class]="(isActive('o2') === true )? ' active' : ''" (click)="select('o2')">Option 2</li>
<li [class]="(isActive('o3') === true )? ' active' : ''" (click)="select('o3')">Option 3</li>
</ul>
......
</li>
</ul>
</div>
//in your component section
select(option:string){
this.selectedLi=option;
}
public isActive(item) {
if(this.selectedLi === item){
return true;
}