Nglf is a structural directive that conditionally includes a template based on the value of an expression evaluated to Boolean.
When the expression evaluates to true, Angular renders the template provided in a then clause, and when it is false or null, Angular renders the template provided in an optional else clause.
The default template for the else clause is blank.
<div *ngIf="showElement">
//This element will only be displayed if the "showElement" variable is truthy.
</div>
//You can also use ngIf with an else clause to specify a template to display if the boolean expression is false:
<div *ngIf="showElement; else otherTemplate">
// This element will only be displayed if the "showElement" variable is truthy.
</div>
<ng-template #otherTemplate>
// This element will be displayed if the "showElement" variable is falsy.
</ng-template>
// In the component class, you can bind the value of the showElement variable to a property in the component:
export class MyComponent {
showElement = true;
}
The *ngIf directive is most commonly used to conditionally show an inline template, as we can see in the following example. The default else template is blank.
@Component({
selector: 'ng-if-simple',
template: `
<button (click)="show = !show">{{ show ? 'hide' : 'show' }}</button>
show = {{ show }}
<br />
<div *ngIf="show">Text to show</div>
`,
})
export class NgIfSimple {
show = true;