Write a Structural Directive in Angular

John Lindquist
InstructorJohn Lindquist

Share this video with your friends

Send Tweet
Published 6 years ago
Updated 4 years ago

Structural directives enable you to use an element as a template for creating additional elements. Creating structural directives requires a knowledge of <template> elements, but they're easy and extremely powerful once you undrestand the concepts.

[00:00] A structural directive deals heavily with templates, let's create one from scratch just to show what's going on. We'll have a selector of an attribute of three, export a class called "ThreeDirective." Add that to our declarations.

[00:22] Add the ThreeDirective to our h1 here, I'll say "three." Then, we'll get a bit of info off of it by saying "constructor." We want to inject the element ref so we can see what element this is on. We actually, instead of just the "ElementRef," we want to see the native element itself, the actual element on the DOM.

[00:46] When I render this out and do this, you see it logs out this actual element just as if you'd selected it and added it to the console. The native element itself is this rendered out element from the template.

[01:00] For a structural directive, we're going to add in an asterisk. When I hit "Save," you'll see something much different, because you'll see nothing on the DOM now. You'll see "template bindings" is what's logged out as the native element.

[01:15] Essentially, what's happened is that instead of three like this, adding the asterisk wraps you element in a template. I'll bring this up, and then adds "three" here. If I hit "Save," now, this will accomplish the exact same thing.

[01:35] You'll see we'll get the template bindings comment. But the asterisk version of a directive is essentially the shorthand for wrapping something in a template element, which will allow us to use this as a template inside of our directive.

[01:50] To use that element, I'm going to inject a couple things, point to inject the "ViewContainerRef." Because it's on a template, remember what this looked like when we wrapped it with the template so this is actually a directive on a template, we can inject the template, as well. This just requires a generic of "any."

[02:17] From here with these two pieces with the view container and a template, if I just use a lifecycle hook like "ngAfterViewInit" to say "this.view.createEmbeddedView(this.template)." Then do that three times.

[02:36] When I hit "Save," I'll now have three "Hello, Angulars" on the page, because I used my "*three" directive.

[02:46] Remember, that surrounded this with the template. Now, I have this template to pass around where it's been passed into my directive. I can just use my ViewContainerRef to create those embedded views using my template and stamp out as many as I need.

François Chabbey
François Chabbey
~ 4 years ago

Thanks for the le