Creating a Structural Directive
In this lesson, we'll look at how to create structural directives.
We'll cover the following...
We’ll be creating another directive that will replace the ngFor
directive. The last directive we created was an attribute directive. The ngFor
directive is a structural directive because it adds/removes elements from the document.
Generating a directive
In the command line, run the following command:
ng generate directive loop
Two files are created: loop.directive.ts
and loop.directive.spec.ts
. We’ll be focusing on the loop.directive.ts
file. Structural directives aren’t all that different from attribute directives in the way that they’re created.
Referencing the elements
The next step is to grab the element to which the directive is applied. In the directive, we’ll need to import two classes: ViewContainerRef
and TemplateRef
.
import { Directive, ViewContainerRef, TemplateRef } from '@angular/core';
The ViewContainerRef
class will give us a reference to the element to which we’re applying the directive. It’s similar to the ElementRef
class. The difference between the two is that the ViewContainerRef
class will expose methods ...