Angular - ngIf

The ngIf statement is used to setup an if statement on an html page.

You use it to stop blocks of html from being rendered.

Note: Newer versions of Angular have a replacement construct.

Here is an example.

note-type-list.component.html

here is a part of an html file. It’s a Grid List control provided by Material

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<mat-grid-list cols="4" rowHeight="170px" gutterSize="5px">
<mat-grid-tile *ngFor="let noteType of noteTypes">
<mat-card class="my-card">
<mat-card-content>
{{noteType.id}}<br>
<span *ngIf="!this.companyKey">
{{noteType.companyKey}}<br>
</span>
<span *ngIf="!this.applicationKey">
{{noteType.applicationKey}}<br>
</span>
{{noteType.applicationSubKey}}<br>
{{noteType.noteType}}<br>
</mat-card-content>
<mat-card-footer>
<button mat-stroked-button
(click)="onRowClicked(noteType)"
class='actionButton'>details
</button>
</mat-card-footer>
</mat-card>
</mat-grid-tile>

Notice the following

1
2
3
<mat-grid-tile *ngFor="let noteType of noteTypes">
:
</mat-grid-tile>

*ngFor starts a loop. The loop will step through each object contained in the noteTypes collection.

For each item in the loop, <mat-grid-tile>..</mat-grid-tile> will be rendered

Also, notice this

1
2
3
4
5
6
7
8
9
10
11
12
<mat-card class="my-card">
<mat-card-content>
{{noteType.id}}<br>
<span *ngIf="!this.companyKey">
{{noteType.companyKey}}<br>
</span>
<span *ngIf="!this.applicationKey">
{{noteType.applicationKey}}<br>
</span>
{{noteType.applicationSubKey}}<br>
{{noteType.noteType}}<br>
</mat-card-content>

with this block a card object will be rendered. It’s showing different attributes of the noteType object.

Notice this

1
2
3
<span *ngIf="!this.companyKey">
{{noteType.companyKey}}<br>
</span>

The *ngIf is an if statement.

if this.companyKey as a value then in an if statement like “this.companyKey” would return a true.

if this.companyKey does not have a value, then in an if statement like “!this.companyKey” would return a true.

so basically - if companyKey has a value then the span tags, and the contents of the <span>..</span> will not be rendered. In this particular case this.companyKey is a different variable then noteType.companyKey.