Author avatar

Yallaling Goudar

Attaching and Detaching Content with ngIf in Angular

Yallaling Goudar

  • Jun 30, 2020
  • 7 Min read
  • 67 Views
  • Jun 30, 2020
  • 7 Min read
  • 67 Views
Languages Frameworks and Tools
Front End Web Developer
Client-side Frameworks
Angular

Introduction

In this guide, you will learn about the ngIf structural directive. This guide looks at how Angular manipulates the DOM with structural directives and how to use the ngIf directive to do the same thing.

Structural Directives

To understand the ngIf directive better, let's first look at structural directives. Structural directives are responsible for the HTML layout in apps. Structural directives shape or reshape the DOM's structure, typically by attaching, detaching, and manipulating the host elements to which they are attached.

1
2
3
4
5
6
<p *ngIf='true'>
  Expression is true and ngIf is true.
</p>
<p *ngIf='false'>  
  Expression is false and ngIf is false.
</p>
html

Some of the more common built-in structural directives include:

  • NgIf—conditionally creates or destroys subviews from the template
  • NgFor—repeats a node for each item in a list
  • NgSwitch—a set of directives that switches among alternative views

As with other directives, you apply a structural directive to a host element. The directive then does whatever it's supposed to do with that host element and its descendants.

Structural directives are easy to recognize. An asterisk (*) precedes the directive attribute name, as shown in the below examples.

1
2
3
4
5
6
7
8
9
10
11
12
<div *ngIf="employee" class="name">{{employee.name}}</div>

<ul>
  <li *ngFor="let employee of employees">{{employee.name}}</li>
</ul>

<div [ngSwitch]="employee?.designation">
  <app-teacher    *ngSwitchCase="'teacher'"    [employee]="employee"></app-teacher>
  <app-clerk *ngSwitchCase="'clerk'"      [employee]="employee"></app-clerk>
  <app-principal *ngSwitchCase="'principal'" [employee]="employee"></app-principal>
  <app-unknown-employee *ngSwitchDefault  [employee]="employee"></app-unknown-employee>
</div>
html

Throughout this guide, you'll see a directive spelled in both UpperCamelCase and lowerCamelCase. You've already seen NgIf and ngIf. There's a reason for the difference in cases. NgIf refers to the directive class; ngIf refers to the directive's attribute name.

A directive class is spelled in UpperCamelCase (NgIf). A directive's attribute name is spelled in lowerCamelCase (ngIf). This guide refers to the directive class when talking about its properties and what the directive does. It refers to the attribute name when describing how to apply the directive to an element in the HTML template.

There are two other kinds of Angular directives, described extensively elsewhere: 1) components and 2) attribute directives. A component manages a region of HTML in the manner of a native HTML element. Technically, it's a directive with a template. An attribute directive changes the appearance or behavior of an element, component, or another directive. For example, the built-in NgStyle directive changes several element styles at the same time.

You can apply many attribute directives to one host element. You can only apply one structural directive to a host element.

Attaching Content With the NgIf Directive

NgIf is a structural directive that conditionally includes a template based on the value of an expression coerced to Boolean. When the expression evaluates to true, Angular renders the template provided in a then clause, and when false or null, Angular renders the template provided in an optional else clause. The default template for the else clause is blank.

The shorthand form of the ngIf directive is *ngIf="condition". It is generally used to provide an attribute of the anchor element for the inserted template. Angular expands this into a more explicit version in which the anchor element is contained in an <ng-template> element.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Simple form with shorthand syntax: 
<div *ngIf="condition">Content to render when condition is true.</div>

//Simple form with the expanded syntax:
<ng-template [ngIf]="condition"><div>Content to render when condition is
true.</div></ng-template>

//Form with an "else" block:
<div *ngIf="condition; else elseBlock">Content to render when condition is true.</div>
<ng-template #elseBlock>Content to render when condition is false.</ng-template>

//Shorthand form with "then" and "else" blocks:
<div *ngIf="condition; then thenBlock else elseBlock"></div>
<ng-template #thenBlock>Content to render when condition is true.</ng-template>
<ng-template #elseBlock>Content to render when condition is false.</ng-template>
html

Attaching Alternative Template Using Else

Display else block code when an expression evaluates to false. The else binding points to an <ng-template> element labeled #elseBlock. The template can be defined anywhere in the component view, but is typically placed right after ngIf for readability.

1
2
3
4
5
6
7
8
9
10
11
12
13
@Component({
  selector: 'ng-if-else',
  template: `
    <button (click)="display= !display">{{display ? 'hide' : 'display'}}</button>
    display = {{display}}
    <br>
    <div *ngIf="display; else elseBlock">Text to display</div>
    <ng-template #elseBlock>Alternate text while primary text is hidden</ng-template>
`
})
export class NgIfElse {
  display: boolean = true;
}
html

Using An External Then Template

You can also specify a template that is defined externally by referencing a labeled <ng-template> element. When you do this, you can change which template to use at runtime, as shown in the following example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@Component({
  selector: 'ng-if-then-else',
  template: `
    <button (click)="display = !display">{{display ? 'hide' : 'display'}}</button>
    <button (click)="switchFirst()">Switch First</button>
    display = {{display}}
    <br>
    <div *ngIf="display; then thenBlock; else elseBlock">this is ignored</div>
    <ng-template #firstBlock>First text to display</ng-template>
    <ng-template #secondBlock>Second text to display</ng-template>
    <ng-template #elseBlock>Alternate text while first text is hidden</ng-template>
`
})
export class NgIfThenElse implements OnInit {
  thenBlock: TemplateRef<any>|null = null;
  show: boolean = true;

  @ViewChild('firstBlock', {static: true}) firstBlock: TemplateRef<any>|null = null;
  @ViewChild('secondBlock', {static: true}) secondBlock: TemplateRef<any>|null = null;

  switchFirst() {
    this.thenBlock = this.thenBlock === this.firstBlock? this.secondBlock : this.firstBlock;
  }

  ngOnInit() {
    this.thenBlock = this.firstBlock;
  }
}
typescript

Conclusion

In this guide, we explored how to use the ngIf directive in Angular to build reactive forms. We also learned how to attach a template to the DOM using if, else, and then blocks based on various conditions.

You can learn more about using forms in Angular in another one of my guides: Using Form Builder in Angular.

0