角度4主题背景颜色更改

时间:2019-02-13 06:49:42

标签: angular

我想通过单击角度4 中的相应彩色按钮来更改div的背景颜色。

Picture

如上图所示,每当我要单击任何颜色时,背景都应更改。

1 个答案:

答案 0 :(得分:1)

创建一个名为“ color”的全局变量,并将其设置为默认颜色。还提供了在颜色之间切换的功能。

public color = 'default';
changeColor(color: string) {
    this.color = color
}

在css文件中为每种颜色定义类

.default {
    background-color: #fff;
}

.blue {
    background-color: blue;
}

.red {
    background-color: red;
}

现在,您可以在HTML代码中调用传递颜色字符串作为输入参数的函数。您可以使用这种条件[ngClass] =“ color”来在所需的任何位置获得应用的颜色。

<div [ngClass]="color">
    <button (click)="changeColor('blue')">blue Button</button>
    <button (click)="changeColor('red')">red Button</button>
<div>