⊗jsagPmStDSC 50 of 97 menu

Dynamically Changing Styles in Angular

Using the ngClass and ngStyle directives, we can bind expressions to elements, allowing our styles to change dynamically.

Let's make the text fade in or out using the active property of the component class:

export class AppComponent { active: boolean = true; toggle() { this.active = !this.active; } }

To do this, we will write a function toggle, which will alternately turn this property on or off:

export class AppComponent { active: boolean = true; toggle() { this.active = !this.active; } }

In the component CSS file, we set the following style for the class:

.hidden { display: none; }

In the component template, we will make a div and add a CSS class hidden to it, which will be turned on or off depending on the active property from the component class:

<div [ngClass]="{hidden: active}"> text </div>

Let's also make a button that, when clicked, will call the toggle method, showing or hiding our component:

<button (click)="toggle()"> toggle </button>

Given three blocks, make three buttons, each of which will toggle its own block.

enru