Author -  Sai gowtham

Conditional Rendering in Angular using *ngIf directive

In this tutorial, we are going to learn about how to render HTML elements conditionally into the dom by using *ngIf directive.

Conditional rendering

It means we only render the elements into the dom whenever the provided data becomes true.

Angular has a special directive called *ngIf which helps us to render the elements conditionally

let’s see an example

app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  isActive = false;}
app.component.html
<div>
    <h1 *ngIf="isActive">You can't see me</h1></div>

In the above code, we have added *ngIf="isActive" to the h1 element so that it only renders into the dom whenever the isActive property becomes true.

Else block

We can also extend the *ngIf directive with else block.

example:

app.component.html
<div>
    <!-- notActive is a reference to else -->
    <h1 *ngIf="isActive; else notActive">You can't see me</h1>    <ng-template #notActive>        <h1>You can see me</h1>
    </ng-template>
</div>

In this example, we have added an else notActive to *ngIf directive and used it inside ng-template so that whenever the isActive property is true the first h1 element will render otherwise the else block h1 element will render into the dom.

If you are confused to write this long-form of code we also have an alternate syntax to use the else block.

app.component.html
<div>
    <h1 *ngIf="isActive">You can't see me</h1>
    <h1 *ngIf="!isActive">You can see me</h1></div>

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY