How to use Angular’s ngIf directive
Angular comes standard with a directive called ngIf directive.
It is a simple if statement, and its usage is to display if the if statement is true.
The way to describe it is as follows.
dell.component.html
<div *ngIf='flg'>
<p>{{flg}}</p>
</div>
dell.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-dell',
templateUrl: './dell.component.html',
styleUrls: ['./dell.component.css']
})
export class DellComponent implements OnInit {
constructor() { }
flg = true;
ngOnInit() {
}
}
flg = true; so the div tag is visible.
Since Angular4, ngIf~else statements can be written.
dell.component.html
<div *ngIf='flg; else Statement'> <!-- Note the enclosed area. -->
<p>{{flg}}</p>
</div>
<ng-template #Statement>
<p>else文です</p>
</ng-template>
If flg is set to false, the following is displayed.
boolean型でない場合の挙動
The variable part of ngIf='variable' is not necessarily of type boolean.
I checked for cases where the behavior is false.
| 値 | 結果 |
|---|---|
| true | true |
| false | false |
| null | false |
| undefined | false |
| [] | true |
| {} | true |
| 0 | false |
| 1 | true |
| -1 | true |
To use ngIf, the following must be imported in app.module.ts
import { FormsModule } from '@angular/forms';
imports [
BrowserModule,
FormsModule
]





コメント