As we mentioned at the beginning of this chapter, the third type of directive is called structural directives, and as the name suggests, those directives are meant to manipulate the element that they applied on. Angular core includes several directives that manipulate the DOM, such as ngIf,
ngFor, and ngSwitch.
For our example, we will implement our own ngIf directive that behaves just like the original one.
First, create a new file named only-if.ts and let's define the basic structure for our directive:
[only-if.ts]
import { Directive } from '@angular/core';
@Directive({
selector: '[onlyIf]' })
export class OnlyIf { }
The structural directives begin their lives just like an attribute directive. We import the
@Directive decorator from the Angular core and declare the selector as an attribute.
Next, we will need to access the template, and we will need some kinds of container so we can attach or remove views. For this, we will need to inject TemplateRef and ViewContainerRef:
[only-if.ts]
import { Directive, TemplateRef, ViewContainerRef
} from '@angular/core';
@Directive({
selector: '[onlyIf]' })
export class OnlyIf {
constructor(private _templateRef: TemplateRef,
private _viewContainerRef: ViewContainerRef) { }
}
Our directive, just like the Angular ngIf, needs to receive a Boolean from its caller that represents the condition on which the content will be shown or removed. For this, we will declare an input for this condition and make use of ViewContainerRef and TemplateRef:
[only-if.ts]
import { Directive, Input,
TemplateRef, ViewContainerRef } from 'angular/core';
@Directive({
selector: '[onlyIf]' })
export class OnlyIf {
constructor(private _templateRef: TemplateRef<any>,
private _viewContainerRef: ViewContainerRef) { } @Input()
set onlyIf(condition:boolean) { if (condition) {
this._viewContainerRef.createEmbeddedView(this._templateRef);
} else {
this._viewContainerRef.clear();
} } }
Let's make use of this directive. Open app.component.ts and paste the following code:
[app.component.ts]
import { Component } from '@angular/core';
@Component({
selector: 'app-root', template: `
<input type="checkbox" [(ngModel)]="condition">
<p *onlyIf="condition">
This content will shown only if the condition is true </p>
` })
export class AppComponent {}
Don't forget to add the OnlyIf class to the declarations attribute of the root module.
Let's explore what's going on: when we use the asterisk (*) to call our directive, Angular creates a <template> tag behind the scenes. Inside our directive, we can get a reference for this template through the TemplateRef class. Then, we can use the ViewContainerRef class, which
represents a container so that we can embed a view into it, to create or clear a view from the content of the template.
Summary
In Angular 2, there are three types of directive: component directive, attribute directive, and structural directive. Throughout this chapter, we got a quick introduction to them and learned how to build simple directives. Directives can do much more, but that's beyond the scope of this book.
Index
A
accordion component
about / The accordion component
accordion tab, implementing / The accordion component tree, extending / Extending the accordion component tree life cycle / The component life cycle
Ahead of Time (AoT) / Bootstrapping the application angular-cli
installing / Installing angular-cli
URL / Generating an Angular 2 project Angular 1
Model-View-Controller pattern / MVC in Angular 1 Angular 2
development environment, preparing / Preparing our development environment, Preparing our development environment, Preparing our development environment components / Components and directives in Angular 2
directives / Components and directives in Angular 2
attribute directive / Components and directives in Angular 2 structural directive / Components and directives in Angular 2 Angular 2 application
breaking, into components / Breaking the application into components Angular 2 project
generating / Generating an Angular 2 project Angular application
bootstrapping / Bootstrapping the application annotations
versus decorators / Decorators versus annotations
Application component / Breaking the application into components asterisk (*)
about / The asterisk – * example / The asterisk – * attribute directive
about / Components and directives in Angular 2, The basic attribute directive ElementRef class / ElementRef and Renderer
Renderer class / ElementRef and Renderer
events, reacting from host element / Reacting to events from the host element properties, passing / Passing properties to the directive
B
basic types, TypeScript about / The basic types bootstrap
dependencies, importing / Importing dependencies tooltip component / Bootstrap tooltip component collapse component / Bootstrap collapse component Button component / Breaking the application into components
C
classes, in TypeScript about / Classes collapse component
reference link / Bootstrap collapse component components
defining / Defining components component selector
about / The component selector options / Selector options component template
about / The component template
styles, embedding in / Embedding styles in component template Controller
about / The Model-View-Controller pattern core directives
about / Core directives NgIf directive / NgIf
NgClass directive / NgClass NgStyle directive / NgStyle NgSwitch directive / NgSwitch NgFor directive / NgFor
custom events
emitting / Emitting custom events
local variable, referencing with / Referencing with a local variable custom types, TypeScript
about / The custom types
D
data
passing, via properties / Passing data via properties data bindings / Data bindings
data interpolation / Data interpolation decorators
using / Using decorators about / Using decorators
versus annotations / Decorators versus annotations default exports
about / The default exports dependencies
managing, with modules / Managing dependencies with modules
E
ElementRef class
about / ElementRef and Renderer encapsulation mode
about / Encapsulation modes emulated / Encapsulation modes native / Encapsulation modes none / Encapsulation modes example / Encapsulation modes event binding / Event bindings
events
reacting, from host element / Reacting to events from the host element export statement
about / The export and import statements
F
Form component / Breaking the application into components
G
generics
about / About generics reference / About generics
H
host element
events, reacting from / Reacting to events from the host element
I
import statement
about / The export and import statements inline template
example / The component template
Input component / Breaking the application into components integrated development environment (IDE)
selecting / Choosing an IDE
L
life cycle events
interfaces / Life cycle event interfaces OnInit method / OnInit and OnDestroy OnDestroy method / OnInit and OnDestroy OnChanges method / OnChanges
about / Other life cycle events local variable
referencing with / Referencing with a local variable example / Referencing with a local variable
Long Time Support(LTS) URL / Installing Node
M
Model
about / The Model-View-Controller pattern Model-View-Controller pattern
working / The Model-View-Controller pattern Model / The Model-View-Controller pattern View / The Model-View-Controller pattern Controller / The Model-View-Controller pattern in Angular 1 / MVC in Angular 1
Model View ViewModel (MVVM) about / MVC in Angular 1 Model / MVC in Angular 1 View / MVC in Angular 1
ViewModel / MVC in Angular 1 modules
about / Managing dependencies with modules
dependencies, managing with / Managing dependencies with modules export statement / The export and import statements
import statement / The export and import statements default exports / The default exports
N
NgClass directive / NgClass NgFor directive
about / NgFor example / NgFor NgIf directive
about / NgIf
asterisk (*) / The asterisk – * NgStyle directive
about / NgStyle example / NgStyle
NgSwitch directive / NgSwitch node
about / Node and npm installing / Installing Node URL / Installing Node npm
about / Node and npm installing / Introducing npm URL / Introducing npm
O
OnChanges method / OnChanges
OnDestroy method / OnInit and OnDestroy OnInit method / OnInit and OnDestroy
P
properties
data, passing via / Passing data via properties property binding / Property bindings
Q
Query children components
parent component, used / Querying child components with the parent component example / Querying child components with the parent component
R
Renderer class
about / ElementRef and Renderer
S
shadow DOM / The shadow DOM structural directive
about / Components and directives in Angular 2, The basic structural directive example / The basic structural directive
styles / Embedding styles in component template
styles property / Embedding styles in component template
T
.ts
reference / The custom types
TaskList component / Breaking the application into components TaskRow component / Breaking the application into components
checkbox / Breaking the application into components label / Breaking the application into components trash / Breaking the application into components template strings / The component template
two-way data binding / Two-way bindings TypeScript
about / Introduction to TypeScript TypeScript interfaces
URL / Life cycle event interfaces type system
about / The type system basic types / The basic types custom types / The custom types generics / About generics
typings
URL / The custom types
V
View
about / The Model-View-Controller pattern view
switching, to components / Moving from views to components ViewModel
about / MVC in Angular 1 VSCode
URL / Choosing an IDE
W
webstorm
reference link / Choosing an IDE