在Angular中,可以使用条件运算符(? :
)来实现多个ngClass
值之间的互相取消。
以下是一个示例代码:
HTML模板:
组件类:
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
condition1: boolean = true;
condition2: boolean = false;
condition3: boolean = true;
toggleClass1() {
this.condition1 = !this.condition1;
}
toggleClass2() {
this.condition2 = !this.condition2;
}
toggleClass3() {
this.condition3 = !this.condition3;
}
}
在上面的示例中,ngClass
指令绑定到一个对象,该对象的键是类名,值是一个布尔值,当布尔值为true
时,对应的类名将会被添加到元素上,当布尔值为false
时,对应的类名将会被移除。
你可以在组件类中使用方法来改变条件的值,从而实现类名的切换。在示例中,我们定义了三个条件变量condition1
,condition2
和condition3
,并提供了一个toggleClass
方法来切换它们的值。
当你调用toggleClass1
、toggleClass2
或toggleClass3
方法时,对应的条件变量的值将会被取反,从而改变类名的状态。
希望这个示例能够帮助到你!
上一篇:Angular - 多个模块