*NgIf: It removes or recreates a part of DOM tree depending on an expression evaluation. It is a structural directive and structural directives alter the layout of the DOM by adding, replacing and removing its elements.
If our component is not ready and waiting for data from server, then we can add loader using *ngIf. Steps:
First declare a boolean:
loading: boolean = false;
Next, in your component add a lifecycle hook called ngOnInit
ngOnInit() {
this.loading = true;
}
and after you get complete data from server set you loading boolean to false.
this.loading=false;
In your html template use *ngIf with the loading
property:
<div *ngIf="loading" class="progress">
<div class="progress-bar info" style="width: 125%;"></div>
</div>
<p class="alert alert-success" *ngIf="names.length > 2">Currently there are more than 2 names!</p>
NgFor provides Some values that can be aliased to local variables
<div *ngFor="let note of csvdata; let i=index; let lastcall=last">
<h3>{{i}}</h3> <-- to show index position
<h3>{{note}}</h3>
<span *ngIf="lastcall">{{anyfunction()}} </span><-- this lastcall boolean value will be true only if this is last in loop
// anyfunction() will run at the end of loop same way we can do at start
</div>
While you are not allowed to use *ngIf
and *ngFor
in the same div (it will gives an error in the runtime) you can nest the *ngIf
in the *ngFor
to get the desired behavior.
Example 1: General syntax
<div *ngFor="let item of items; let i = index">
<div *ngIf="<your condition here>">
<!-- Execute code here if statement true -->
</div>
</div>
Example 2: Display elements with even index
<div *ngFor="let item of items; let i = index">
<div *ngIf="i % 2 == 0">
{{ item }}
</div>
</div>
The downside is that an additional outer div
element needs to be added.
But consider this use case where a div
element needs to be iterated (using *ngFor) and also includes a check whether the element need to be removed or not (using *ngIf), but adding an additional div
is not preferred. In this case you can use the template
tag for the *ngFor:
<template ngFor let-item [ngForOf]="items">
<div *ngIf="item.price > 100">
</div>
</template>
This way adding an additional outer div
is not needed and furthermore the <template>
element won't be added to the DOM. The only elements added in the DOM from the above example are the iterated div
elements.
Note: In Angular v4 <template>
has been deprecated in favour of <ng-template>
and will be removed in v5. In Angular v2.x releases <template>
is still valid.