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.

Directives (custom or platform) like any other Angular artifact, always belong to a module. To use them across modules, the module needs to be imported. Wondering where ngStyle is defined? ngStyle is part of the core framework module, CommonModule,, and has been imported in the workout runner module definition (workout-runner.module.ts). CommonModule defines a number of handy directives that are used across Angular.

Well! That covers everything we had to learn about our newly developed view.

And as described earlier, if you are having a problem with running the code, look at the Git branch checkpoint2.2. If not using Git, download the snapshot of checkpoint2.2 (a ZIP file) from http://bit.ly/ng2be-checkpoint2-2. Refer to the README.md file in the trainer folder when setting up the snapshot for the first time.

Time to add some enhancements and learn a bit more about the framework!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset