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...