In Angular, if data is the thing that makes an application come to life, then directives are the thing that makes actions, reactions, and interactions possible.
In the simplest terms, a directive is like a template function that you can use to make things happen. They may take arguments, do something with it, and generate a reactionary action on your HTML. Directives are things that let you attach behaviors to the DOM.
Here’s a quick primer on what directives are, the different types you’ll probably encounter in the wild, and when and how to use them.
The Super-Speedy Low Down on Components
A way to think about your component is that it’s a container that acts as the bridge between your data and your view. It’s the controller portion of an MVC setup — meaning that it connects and renders your processed data from the service (aka model) layer.
When it comes to views, Angular is going to require something to help it figure out how, when, and where to do things. Structural and attribute directives are tools that Angular uses to connect a component to its associated view.
The Low Down on Structural Directives
Structural directives are things that determine how the final structure of a page looks in a rendered instance. They have the power to shape and reshape the final HTML structure by adding, removing, or changing elements.
Take a look at a common piece of Angular directive implementation below:
In the case above, status is set as a string, but it’s actually connected to a variable that exists inside the associated component and is expected to return a boolean value.
From this value, Angular then determines if it’s going to show the host element or not. In our case, the host element is the div that *ngIf currently sits inside.
The * is prefixed to ngIf so that Angular knows what kind of behavior type it’s expected to perform on the host element. In the grand scheme of Angular, * is actually a shorthand version of writing <ng-template [ngIf]="status"> your div here </ng-template>
When you don’t have a suitable host element available, Angular lets you use <ng-container> as the placeholder. Then, you don’t have to resort to littering your code with <span> that may have other things like styling and specially configured behaviors attached to it.
<ng-container *ngIf="hasCat"> with her cat</ng-container>
There are multiple structural directives available, and they’re actions that give your application the ability to perform choices based on the logic as dictated by the component.
ngIf is a commonly used structural directive. The other two are ngFor and ngSwitch.
This post is for paying subscribers only
Sign up now and upgrade your account to read the post and get access to the full library of posts for paying subscribers only.