NgIf

As the official documentation states, the ngIf directive removes or recreates a portion of the DOM tree based on an expression. If the expression assigned to the ngIf directive evaluates to false, then the element is removed from the DOM. Otherwise, a clone of the element is reinserted into the DOM. We could enhance our countdown timer by leveraging this directive, like this:

<timer> [seconds]="timeout"></timer>
<p *ngIf="timeout === 0">Time up!</p>

When our timer reaches 0, the paragraph that displays the Time up! text will be rendered on the screen. You have probably noticed the asterisk that prepends the directive. This is because Angular embeds the HTML control marked with the ngIf directive (and all its HTML subtrees, if any) in a   <ng-template> tag, which will be used later on to render the content on the screen. Covering how Angular treats templates is definitely out of the scope of this book, but let's just point out that this is syntactic sugar provided by Angular to act as a shortcut to other, more verbose syntax based on template tags.

Perhaps you are wondering what difference does it make to render some chunk of HTML on screen with *ngIf="conditional" rather than with [hidden]="conditional". The former will clone and inject pieces of templated HTML snippets in the markup, removing it from the DOM when the condition evaluates to false, while the latter does not inject or remove any markup from the DOM. It simply sets the visibility of the already existing chunk of HTML annotated with that DOM attribute.

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

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