Summary

Let’s summarize what we’ve learned about directives in Angular.

We hope that the previous lessons helped you understand directives better. Hopefully, these lessons have created confidence when it comes to implementing custom directives that improve the codebase in future projects!

In this lesson, we’ll quickly go through all the fantastic features of directives that we’ve learned about. Consider this lesson a cheat sheet with all the key points about directives and how to use them.

Directives

Angular distinguishes these three types of directives:

  • Components are directives that have an HTML template.

  • Attribute directives can change the appearance or behavior of any element in Angular. For instance, this directive can highlight some words in the text. The directive NgStyle is an example of an attribute directive.

  • Structural directives can change the DOM layout during runtime by adding or removing DOM nodes. The NgIf directive, for example, is a structural directive.

It’s important to remember that a directive is just a simple class with a special decorator. Here’s an example of a boilerplate for a directive class:

@Directive({
  selector: '[myDirective]'
})
export class MyDirective {
}

We can use a directive by applying it to the element in the template, as illustrated in the following code block:

<div myDirective> Testing my directive </div>

The precise syntax of applying the directive depends on the directive’s selector. The selector can be defined in many ways. Here’s a list of available selectors:

  • The element-name selector is used to select by element name.

  • The .class selector is used to select by class name.

  • The [attribute] selector is used to select by attribute name.

  • The [attribute=value] selector is used to select by attribute name and value.

  • The :not(sub_selector) selector is used to select only if there’s no match with sub_selector.

  • The selector1, selector2 selector is used to select if ...