Outline

Building Structural Directives

We're going to build a structural directive using the APIs provided by Angular. We need to understand two classes:

  1. TemplateRef
  2. ViewContainerRef

TemplateRef Class

The TemplateRef class represents an embedded template. If you recall the full syntax of a structural directive, each directive is wrapped using the <ng-template> element. This container element is never rendered, rather, it contains a reference to the host element that the structural directive is applied to.

We'll use dependency injection to get access to the TemplateRef instance. We can then logically embed the template reference into the view container based on the logic of our directive.

ViewContainerRef Class

The ViewContainerRef class represents the view container into which we'll embed the template. Like the TemplateRef class instance, we'll gain access to the ViewContainerRef class instance via dependency injection on our directive's constructor() function.

While the ViewContainerRef class contains several methods, we'll be focusing on the createEmbeddedView() method. The method instantiates an embedded TemplateRef instance into the view container.

 

I finished! On to the next chapter