我想通过单击按钮来更改父div的背景颜色。
<div>
<p>I want to change the background-color of the parent div by the click of the button.
</p>
<button (click)="changeColour()" id="buy-now">BUY NOW</button>
<div>
您可以有条件地向父div添加一个类([class.red]="isRed"
,并在调用changeColor()
函数(isRed = true
)时更改条件。
不要像JQuery那样考虑它!
但更详细的答案:
您的HTML将使用该类的表达式
<div [ngClass]="{'blue' : isBlue }">
<p>I want to change the background-color of the parent div by the click of the button.
</p>
<button (click)="changeColour()" id="buy-now">BUY NOW</button>
<div>
然后您的TypeScript将切换值。您还可以根据需要使用表达式/类名:
export class AppComponent {
isBlue = false;
changeColour() {
this.isBlue = !this.isBlue;
console.log(this.isBlue);
}
name = 'Angular';
}