Introduction

Directives are instructions in the DOM. It gives support to the connection between the component and the template. The types of directives are: component directives, structural directives and Attribute Directives.

Component Directives

These classes have instruction to handle the component, working with templates. An example is using the @Directive.

When you create your own directive you should use the command:

ng g directive directive_name

It will create the file directive_name.directive.spec.ts and directive_name.directive.ts. It also will be declared in the add.module.ts file. The selector use brackets. Angular will apply the logic in every element with that directive.

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

@Directive({
  selector: '[directive_name]'
})
export class DirectiveNameDirective {
  constructor() { }
}

Structural Directives

Those are used to manipulate the DOM elements (add and remove), changing the structure of the view.

An example is to use * ngIf inside a tag.

<p * ngIf = "isOk>Component created</p>

In this case, if the result is false, the component will not be rendered in the DOM.

Also is commun the ngFor and ngSwitch.

An explanation about the ‘*’ you can see here.

Attibute Directives

Those are used to manipulate the appearance and behavior of the DOM elements.

An example id the ngStyle which can change the color of the component.

References

  • https://angular.io/tutorial/toh-pt3
  • https://www.tutorialspoint.com/angular7/angular7_directives.htm