NgIf

When we want to either display or remove an element from the DOM, we use the NgIf directive. We pass an expression to the directive, and it must evaluate to a Boolean. If it evaluates to true, the element will be displayed on the view. Conversely, if the expression evaluates to false, the element will be removed from the DOM.

Note that we can also bind to the hidden property (property binding will be described as follows) to achieve the same thing, visually, but there is a difference between the property binding method, and using the NgIf directive. The difference is that using property binding on hidden just hides the element, whereas using the NgIf directive physically removes the element from the DOM.

Here is what NgIf looks like in code (in the context of our car example, assume we had a horsepower property):

<ul *ngFor="let car of cars">
<li *ngIf="car.horsepower > 350">
The {{ car.make }} {{ car.model }} is over 350 HP.
</li>
</ul>

In most traditional programming languages when there are alternate things to check for in sequence, as in a series of traditional ifthen, and else statements, it sometimes makes more sense to use a switch statement (if the language supports one). Java, JavaScript, and TypeScript are examples of languages (and there are, of course, many others) that support this conditional construct. Angular gives this power to us as well, so we can be more expressive and efficient with our code.

Let's take a look at how this is accomplished in Angular in the next section.

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

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