Photo by ConvertKit on Unsplash

What Are ‘Directives’ in Angular?

Vanessa Martinez
2 min readJan 24, 2021

--

When working in Angular, you have the ability to give the DOM instructions. More specifically, you’re able to control certain element(s). It’s a cool feature called a “directive,” and there are actually 3 kinds:

Components - directives with a template

Attribute Directives - change behavior or appearance of elements

Structural Directives - change the DOM layout (adding/removing elements)

Components

This is the most common type of directive and is written as a TypeScript class with an @Component decorator. Components work as their own template of instructions. Within it, you can specify what should be used.

import { Component } from '@angular/core';

@Component({
selector: 'garden-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'angulargardenapp';
}

Above, the component contains metadata, such as the selector, which allows you to invoke a component from an HTML template. The templateUrl provides the path to the HTML view. The styleUrls is an array, where you can specify all the stylesheets needed for the HTML view.

Attribute Directives

These will change the appearance or behavior of an element, component, or other directive. Some attribute directives come built-in with Angular, such as:

ngClass - used to add or remove CSS classes

ngStyle - used to add or remove HTML styles

ngModel - used to add two-way data binding to an HTML form element

Check out the setGardenStyles() method below. It uses a component property gardenStyles, which sets two styles within an object.

gardenStyles: {}; 
setGardenStyles() {
this.gardenStyles = {
'font-style': this.newUser ? 'bold' : 'italic',
'font-weight': !this.updateProfile ? 'bold' : 'normal'
};
}

Then, we use property binding with the ngStyle directive (written enclosed in square brackets below) to set a div’s style. You can use ngStyle to set multiple inline styles too.

<div [ngStyle]="gardenStyles">   
Hello, welcome to the garden!
</div>

Structural Directives

These control the structure of the DOM, usually by adding, removing, or altering an element. Among others, Angular’s built-in structural directives include:

ngIf - used to conditionally include a template

ngFor - used to repeat a node for every item in a list

ngSwitch - directives that change depending on the view

Notice the ngFor directive below. It’s preceded by an asterisk (*).

<div *ngFor="let tool of tools">{{tool.name}}</div>

Above, we’re defining how each item should be rendered. In this case, we’re displaying each tool’s name.

There’s plenty more to learn on directives. This was a quick introduction. For more info, check out the resources below.

References:

--

--

Vanessa Martinez

Freelance Software Engineer. Experience in JavaScript, React.js, and Ruby on Rails.