We can use style property of div for adding css .

1. First way:

app.component.html

<div>
<div [style.background-color]="getStyle()">
Click button to change my color
</div>
<button (click)="show = !show;">Toggle style</button>
</div>

app.component.ts

show: false;

getStyle() {
if (this.show) {
return "red";
} else {
return "";
}
}

2. Second way for adding multiple css classes:

app.component.html

<div>
<div [ngClass]="{'styleClass': changeColor,'changeText': changeColor}">
Click button to change my color
</div>
<button (click)="getStyle()">style</button>
</div>

app.component.ts

changeColor: boolean = false;

getStyle() {
this.changeColor = !this.changeColor;
if (this.changeColor) {
return "yellow";
} else {
return "";
}
}

app.component.css

.styleClass {
background-color: red;
}
.changeText {
color: blue;
}

3.  For adding single css class.

app.component.html

<div [class.styleClass]="isClassVisible">
Click button to change my color
</div>
Conditionally changing styles to an element in Angular 2/4
Tagged on:                     

Leave a Reply

Your email address will not be published. Required fields are marked *