Custom Structural Directives in Angular

Donovan
3 min readJan 30, 2022

Grab a plate, grab a glass

Directives are used to manipulate the DOM directly, to change the appearance as needed. Angular has built in structural and attribute directives. Those can be found on their guide here https://angular.io/guide/built-in-directives .

The purpose of this demo is to show how to create your own custom structural directive. It will cover generation, configuration/implementation, and how to use. We will make a structural directive that will remove components and html elements based on a condition.

The code for this example can be found on my github here

https://github.com/dreedsanders/custom-structural-directive

The command to generate an angular directive is

ng generate directive custom-name

This command creates two files, one for implementation and one for testing. It also imports and adds the new directive to the declarations array in your app.module.ts file.

For any structural directive you will need modules that allow you to access and change html elements in your components. These are the modules that will need to be imported into your directive.

import { Directive, TemplateRef, ViewContainerRef, Input } from ‘@angular/core’;

Since you will be using TemplateRef and ViewContainerRef methods, it is necessary to have instances of each. Pass them in your constructor method

constructor(private tempRef: TemplateRef<any>, private viewCon: ViewContainer){}

Your directive is what will be used to access or change html elements of your application. The function listening for a user interaction should be titled in a way that reflects the action to happen. ‘@Input’ is used to relay information from that user interaction to your method.

custom structural directive in Angular
Custom Structural Directive Class

In your app.component.ts file create a property with a condition, true or false, that you want to use in your html.

Donovan

Learning. Puttin up shots in Angular and Java and Python and anything else I get my hands on. Sights set on becoming a gainfully employed developer.