Styling HTML with ngClass and ngStyle
Angular has two excellent directives that allow us to dynamically set styles on any element and toggle CSS classes. For the bootstrap progress bar, we use the ngStyle directive to dynamically set the element's style, width, as the exercise progresses:
<div class="progress-bar" role="progressbar" ...
[ngStyle]="{'width':(exerciseRunningDuration/currentExercise.duration) * 100 + '%'}"> </div>
ngStyle allows us to bind one or more styles to a component's properties at once. It takes an object as a parameter. Each property name on the object is the style name, and the value is the Angular expression bound to that property, such as the following example:
<div [ngStyle]= "{ 'width':componentWidth, 'height':componentHeight, 'font-size': 'larger', 'font-weight': ifRequired ? 'bold': 'normal' }"></div>
The styles can not only bind to component properties (componentWidth and componentHeight), but also be set to a constant value ('larger'). The expression parser also allows the use of the ternary operator (?:); check out isRequired.
If styles become too unwieldy in HTML, we also have the option of writing in our component a function that returns the object hash, and setting that as an expression:
<div [ngStyle]= "getStyles()"></div>
Moreover, getStyles on the component looks as follows:
getStyles () { return { 'width':componentWidth, ... } }
ngClass works on the same lines too, except that it is used to toggle one or multiple classes. For example, check out the following code:
<div [ngClass]= "{'required':inputRequired, 'email':whenEmail}"></div>
The required class is applied when inputRequired is true and is removed when it evaluates to false.
Well! That covers everything we had to learn about our newly developed view.
Time to add some enhancements and learn a bit more about the framework!