以下是一个使用Angular来通过点击按钮添加和更改类的示例代码:
button.component.ts
:import { Component } from '@angular/core';
@Component({
selector: 'app-button',
template: `
`,
styles: [
`
.active {
background-color: blue;
color: white;
}
`
]
})
export class ButtonComponent {
isActive = false;
toggleActive() {
this.isActive = !this.isActive;
}
}
app.component.html
:
app.module.ts
中导入和声明该按钮组件:import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { ButtonComponent } from './button.component';
@NgModule({
declarations: [AppComponent, ButtonComponent],
imports: [BrowserModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
这个示例中,我们创建了一个名为ButtonComponent
的Angular组件,它包含一个按钮和一个名为isActive
的属性。通过点击按钮,我们可以切换isActive
属性的值,从而添加或删除active
类。通过CSS样式定义了active
类的样式,当active
类存在时,按钮的背景颜色将变为蓝色,并且文字颜色将变为白色。
注意:为了使这个示例正常运行,确保你已经正确安装了Angular CLI,并且已经创建了一个新的Angular项目。