Angular Built-in Structural Directives

Angular Built-in Structural Directives

There are three kinds of directives in Angular:

Components—directives with a template.
Structural directives—change the DOM layout by adding and removing DOM elements.
Attribute directives—change the appearance or behavior of an element, component, or another directive.

Components are the most common of the three directives. You saw a component for the first time in the QuickStart guide.

Structural Directives change the structure of the view. Two examples are NgFor and NgIf. Learn about them in the Structural Directives guide.

Attribute directives are used as attributes of elements. The built-in NgStyle directive in the Template Syntax guide, for example, can change several element styles at the same time.

NgIf directive

npm Package @angular/common
Module import { NgIf } from ‘@angular/common’;
Source common/src/directives/ng_if.ts

Overview
@Directive({ selector: ‘[ngIf]’ })
class NgIf {
set ngIf: any
set ngIfThen: TemplateRef<NgIfContext> | null
set ngIfElse: TemplateRef<NgIfContext> | null
}

Selectors
[ngIf]

Inputs
ngIf bound to NgIf.ngIf
ngIfThen bound to NgIf.ngIfThen
ngIfElse bound to NgIf.ngIfElse

Description
Conditionally includes a template based on the value of an expression.

ngIf evaluates the expression and then renders the then or else template in its place when expression is truthy or falsy respectively. Typically the:

then template is the inline template of ngIf unless bound to a different value.
else template is blank unless it is bound.

Most common usage
The most common usage of the ngIf directive is to conditionally show the inline template as seen in this example:

@Component({
selector: ‘ng-if-simple’,
template: `
<button (click)=”show = !show”>{{show ? ‘hide’ : ‘show’}}</button>
show = {{show}}
<br>
<div *ngIf=”show”>Text to show</div>
`
})
class NgIfSimple {
show: boolean = true;
}

Showing an alternative template using else

If it is necessary to display a template when the expression is falsy use the else template binding as shown. Note that the else binding points to a <ng-template> labeled #elseBlock. The template can be defined anywhere in the component view but is typically placed right after ngIf for readability.

@Component({
selector: ‘ng-if-else’,
template: `
<button (click)=”show = !show”>{{show ? ‘hide’ : ‘show’}}</button>
show = {{show}}
<br>
<div *ngIf=”show; else elseBlock”>Text to show</div>
<ng-template #elseBlock>Alternate text while primary text is hidden</ng-template>
`
})
class NgIfElse {
show: boolean = true;
}

Using non-inlined then template

Usually the then template is the inlined template of the ngIf, but it can be changed using a binding (just like else). Because then and else are bindings, the template references can change at runtime as shown in this example.

@Component({
selector: ‘ng-if-then-else’,
template: `
<button (click)=”show = !show”>{{show ? ‘hide’ : ‘show’}}</button>
<button (click)=”switchPrimary()”>Switch Primary</button>
show = {{show}}
<br>
<div *ngIf=”show; then thenBlock; else elseBlock”>this is ignored</div>
<ng-template #primaryBlock>Primary text to show</ng-template>
<ng-template #secondaryBlock>Secondary text to show</ng-template>
<ng-template #elseBlock>Alternate text while primary text is hidden</ng-template>
`
})
class NgIfThenElse implements OnInit {
thenBlock: TemplateRef<any>|null = null;
show: boolean = true;

@ViewChild(‘primaryBlock’)
primaryBlock: TemplateRef<any>|null = null;
@ViewChild(‘secondaryBlock’)
secondaryBlock: TemplateRef<any>|null = null;

switchPrimary() {
this.thenBlock = this.thenBlock === this.primaryBlock ? this.secondaryBlock : this.primaryBlock;
}

ngOnInit() { this.thenBlock = this.primaryBlock; }
}

Storing conditional result in a variable

A common pattern is that we need to show a set of properties from the same object. If the object is undefined, then we have to use the safe-traversal-operator ?. to guard against dereferencing a null value. This is especially the case when waiting on async data such as when using the async pipe as shown in following example:

Hello {{ (userStream|async)?.last }}, {{ (userStream|async)?.first }}!

There are several inefficiencies in the above example:

We create multiple subscriptions on userStream. One for each async pipe, or two in the example above.
We cannot display an alternative screen while waiting for the data to arrive asynchronously.
We have to use the safe-traversal-operator ?. to access properties, which is cumbersome.
We have to place the async pipe in parenthesis.

A better way to do this is to use ngIf and store the result of the condition in a local variable as shown in the the example below:

@Component({
selector: ‘ng-if-let’,
template: `
<button (click)=”nextUser()”>Next User</button>
<br>
<div *ngIf=”userObservable | async as user; else loading”>
Hello {{user.last}}, {{user.first}}!
</div>
<ng-template #loading let-user>Waiting… (user is {{user|json}})</ng-template>
`
})
class NgIfAs {
userObservable = new Subject<{first: string, last: string}>();
first = [‘John’, ‘Mike’, ‘Mary’, ‘Bob’];
firstIndex = 0;
last = [‘Smith’, ‘Novotny’, ‘Angular’];
lastIndex = 0;

nextUser() {
let first = this.first[this.firstIndex++];
if (this.firstIndex >= this.first.length) this.firstIndex = 0;
let last = this.last[this.lastIndex++];
if (this.lastIndex >= this.last.length) this.lastIndex = 0;
this.userObservable.next({first, last});
}
}

Notice that:

We use only one async pipe and hence only one subscription gets created.
ngIf stores the result of the userStream|async in the local variable user.
The local user can then be bound repeatedly in a more efficient way.
No need to use the safe-traversal-operator ?. to access properties as ngIf will only display the data if userStream returns a value.
We can display an alternative template while waiting for the data.

Syntax

Simple form:

<div *ngIf=”condition”>…</div>
<ng-template [ngIf]=”condition”><div>…</div></ng-template>

Form with an else block:

<div *ngIf=”condition; else elseBlock”>…</div>
<ng-template #elseBlock>…</ng-template>

Form with a then and else block:

<div *ngIf=”condition; then thenBlock else elseBlock”></div>
<ng-template #thenBlock>…</ng-template>
<ng-template #elseBlock>…</ng-template>

Form with storing the value locally:

<div *ngIf=”condition as value; else elseBlock”>{{value}}</div>
<ng-template #elseBlock>…</ng-template>

Static Members
Constructor

constructor(_viewContainer: ViewContainerRef, templateRef: TemplateRef<NgIfContext>)

Members

set ngIf: any

set ngIfThen: TemplateRef<NgIfContext> | null

set ngIfElse: TemplateRef<NgIfContext> | null

 

 

NgSwitch directive

npm Package @angular/common
Module import { NgSwitch } from ‘@angular/common’;
Source common/src/directives/ng_switch.ts
NgModule CommonModule

Adds / removes DOM sub-trees when the nest match expressions matches the switch expression.

Overview
@Directive({ selector: ‘[ngSwitch]’ })
class NgSwitch {
set ngSwitch: any
}

How To Use
<container-element [ngSwitch]=”switch_expression”>
<some-element *ngSwitchCase=”match_expression_1″>…</some-element>
<some-element *ngSwitchCase=”match_expression_2″>…</some-element>
<some-other-element *ngSwitchCase=”match_expression_3″>…</some-other-element>
<ng-container *ngSwitchCase=”match_expression_3″>
<!– use a ng-container to group multiple root nodes –>
<inner-element></inner-element>
<inner-other-element></inner-other-element>
</ng-container>
<some-element *ngSwitchDefault>…</some-element>
</container-element>

Selectors
[ngSwitch]

Inputs
ngSwitch bound to NgSwitch.ngSwitch

Description
NgSwitch stamps out nested views when their match expression value matches the value of the switch expression.

In other words:

you define a container element (where you place the directive with a switch expression on the [ngSwitch]=”…” attribute)
you define inner views inside the NgSwitch and place a *ngSwitchCase attribute on the view root elements.

Elements within NgSwitch but outside of a NgSwitchCase or NgSwitchDefault directives will be preserved at the location.

The ngSwitchCase directive informs the parent NgSwitch of which view to display when the expression is evaluated. When no matching expression is found on a ngSwitchCase view, the ngSwitchDefault view is stamped out.

Members
set ngSwitch: any

 

IT Professionals, Web Developers, web programmers, IT students can Apply for the certification course.

Angular 4 Tutorial IndexBack to Angular 4 Tutorial Main Page

Angular Built-in Attribute Directives
Pipes

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?