在Angular中通过脚本改变
HTML模板:
这是一个div
组件代码:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
backgroundColor: string = 'red';
changeColor() {
this.backgroundColor = 'blue';
}
}
在上面的示例中,通过属性绑定将backgroundColor
变量绑定到
style.background
属性上,初始颜色为红色。当点击按钮时,通过changeColor()
方法改变backgroundColor
的值为蓝色,从而改变注意:style.background
属性接受的值可以是任何有效的CSS颜色值,如'blue'、'#ff0000'、'rgb(255, 0, 0)'等。