Attributes Directives

Angular attribute directives are a number of built-in directives that we can add to our HTML elements that give them a dynamic behavior.  In summary, an attribute directive changes the appearance or behavior of a DOM element.

Directives Overview

There are three kinds of directives in Angular namely:

  • Components - This is basically a directive with a template.
  • Structural directives – The structural directive changes the DOM layout by adding and removing DOM elements.
  • Attributes directives – This type of directive changes the appearance or behavior of an element, component, or another directive.

Components are the most common of the three directives. Example of a component is as shown below:

TypeScript Code (component.ts):

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent {
  title = 'This is a sample Component!';

Structural Directives change the structure of the view. Two examples are the NgFor and NgIf directives. As an example


<div *ngIf="false" class="name">Welcome to Index Page</div>

Attribute directives are used as attributes of elements.


HTML Code:

<div [ngStyle]="currentStyles">
  This div is initially italic, normal weight, and extra large (24px).

TypeScript Code:

currentStyles: {};
setCurrentStyles() {
  // CSS styles: set per current state of component properties
  this.currentStyles = {
    'font-style':  this.canSave      ? 'italic' : 'normal',
    'font-weight': !this.isUnchanged ? 'bold'   : 'normal',
    'font-size':   this.isSpecial    ? '24px'   : '12px'

Live Demo:

It is just a code snippet explaining a particular concept and may not have any output

See the Pen attributesDirectiveExample by w3resource (@w3resource) on CodePen.

Build a simple attribute directive

An attribute directive minimally requires building a controller class annotated with @Directive, which specifies the selector that identifies the attribute. The controller class implements the desired directive behavior.

We will demonstrate building a simple appHighlight attribute directive to set an element's background color when the user hovers over that element.


<p appHighLight> Hover to Highlight</p>

Write the directive code

Create the directive class file in a terminal window with the CLI command ng generate directive.

ng generate directive highlight

The CLI creates highlight.directive.ts, a corresponding test file (.spec.ts, and declares the directive class in the root AppModule.

The generated highlight.directive.ts is as shown below

TypeScript Code:

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

  selector: '[appHighlight]'
export class HighlightDirective {
  constructor() { }

The imported Directive symbol provides Angular @Directive decorator.

The @Directive decorator's lone configuration property specifies the directive's CSS attribute selector, [appHighlight].

It's the brackets ([]) that make it an attribute selector. Angular locate each element in the template that has an attribute named appHighlight and applies the logic of this directive to that element.

The attribute selector pattern explains the name of this kind of directive.

Why not "highlight"?

Though highlight would be a more concise selector than appHighlight and it would work, the best practice is to prefix selector names to ensure they don't conflict with standard HTML attributes. This also reduces the risk of colliding with third-party directive names. The CLI added the app prefix for you.

Make sure you do not prefix the highlight directive name with ng because that prefix is reserved for Angular and using it could cause bugs that are difficult to diagnose.

After the @Directive metadata comes the directive's controller class, called HighlightDirective, which contains the (currently empty) logic for the directive. Exporting HighlightDirective makes the directive accessible.

Now edit the generated highlight.directive.ts to look as follows

TypeScript Code (The edited highlight.directive.ts):

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

  selector: '[appHighlight]'
export class HighlightDirective {
    constructor(el: ElementRef) {
       el.nativeElement.style.backgroundColor = 'yellow';

The import statement specifies an additional ElementRef symbol from the Angular core library:

You use the ElementRef in the directive's constructor to inject a reference to the host DOM element, the element to which you applied appHighlight.

ElementRef grants direct access to the host DOM element through its nativeElement property.

This first implementation sets the background color of the host element to yellow.

Apply the attribute directive

As shown in component.html above, to use the new HighlightDirective, add a paragraph (

) element to the template of the root AppComponent and apply the directive as an attribute.

<p appHighlight>Hover to Highlight!</p>

Now run the application to see the HighlightDirective in action.

ng serve

In summary, Angular found the appHighlight attribute on the host <p> element. It created an instance of the HighlightDirective class and injected a reference to the <p> element into the directive's constructor which sets the <p> element's background style to yellow.

Previous: Angular Elements
Next: Pipes

Share this Tutorial / Exercise on : Facebook and Twitter