Building  Large-Scale Web Applications with Angular
上QQ阅读APP看书,第一时间看更新

Style and class binding

We use class binding to set and remove a specific class based on the component state, as follows:

[class.class-name]="expression" 

This adds class-name when expression is true and removes it when it is false. A simple example can look as follows:

<div [class.highlight]="isPreferred">Jim</div> // Toggles the highlight class 

Use style bindings to set inline styles based on the component state:

[style.style-name]="expression";

While we have used the ngStyle directive for the workout view, we could have easily used style binding as well, as we are dealing with a single style. With style binding, the same ngStyle expression would become the following:

[style.width.%]="(exerciseRunningDuration/currentExercise.duration) * 100" 

width is a style, and since it takes units too, we extend our target expression to include the % symbol.

Remember that style. and class. are convenient bindings for setting a single class or style. For more flexibility, there are corresponding attribute directives: ngClass and ngStyle.

Earlier in the chapter, we formally introduced directives and their classifications. One of the directives types, attribute directives (again, don't confuse them with attribute binding, which we introduced in the preceding section) are the focus of our attention in the next section.