ngIf Structural Directives In Angular

1 min read
Table of contents

Structural directives in Angular are used to change the structure of the DOM by adding, removing, or changing elements dynamically. They start with an asterisk (*
) and modify the HTML layout.
Create A Component
ng generate component component/Directive
*ngIf
Import CommonModule in Directives.component.ts
import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
@Component({
selector: 'app-directive',
imports: [CommonModule],
templateUrl: './directive.component.html',
styleUrl: './directive.component.css',
})
export class DirectiveComponent {
isdiv1: boolean = false;
isdiv2: boolean = false;
isToggle: boolean = true;
hide() {
this.isdiv1 = false;
}
show() {
this.isdiv1 = true;
}
toggle() {
this.isToggle = !this.isToggle;
}
}
Add directive.component.html
Displays an element based on a condition.
<div class="container">
<div class="row row-cols-2 row-cols-lg-2">
<div class="col">
<div *ngIf="isdiv1" class="p-3 bg-primary">Div 1</div>
</div>
<div class="col">
<div *ngIf="isToggle" class="p-3 bg-success">Div 2 </div>
</div>
</div>
<div class="row row-cols-2 row-cols-lg-2">
<div class="col">
<button (click)="hide()" class="btn btn-danger m-3">Hide</button>
<button (click)="show()" class="btn btn-primary m-3">Show</button>
</div>
<div class="col">
<button (click)="toggle()" class="btn btn-primary m-3">Toggel</button>
</div>
</div>
</div>
0
Subscribe to my newsletter
Read articles from Code Inception directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
