What are Angular directives?

Share

Overview

Directives are HTML attributes. They tell Angular to alter the style of the Dom elements. AngularJS helps us extend HTML with new attributes.

There are three types of directives:

  1. Components directives
  2. Structural directives
  3. Attribute directives
Different types of directives

Component directives

Component directives detail how the component should be processed, instantiated, and used at runtime, forming the main class.

import {Component} from "@angular/core";
//decorator
@Component({
selector: 'my-App',
template: '<h1>{{name}}</h1>'
})
export class ExampleComponent{
name: string = "Angular 2"
}

First, we import a component from "@angular/core". Then, we decorate our ExmapleComponent class with the @component decorator.

Structural directives

Structural directives add or remove the elements from the DOM. Therefore, they are responsible for changing the structure of the DOM.

Structural directives include a * sign before them, for example, *NgSwitch and *ngFor.

<div *ngFor="let book of books">{{book.name}}</div>
<div template="ngFor let book of books">{{book.name}}</div>
<ng-template ngFor let-book [ngFor]="book">{{book.name}}
</ng-template>

In the code above, we use the let keyword to declare an input variable referenced within the template. book is the input variable in this example. The let book is translated into variables named let-book by the parser.

In line 2, we can see that the NgFor directive sets and resets the properties of its context as it loops through the list.

Attribute directives

We use attribute directives to show or hide elements, apply a conditional style to them, or dynamically change a component’s behavior according to a changing property.

They manipulate the DOM by changing its behavior and appearance.

<p [ngStyle]="{'background': isRed ? 'red' : 'green'}"> This is
an Attribute Directive</p>

In the code above, we add a red background if the value of the isRed variable is true. If the value of the isRed variable is false, the background of the above elements will be green.

Code

We can find a working example containing a few concepts discussed in this shot:

import { TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';

describe('AppComponent', () => {
  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  });

  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    expect(app).toBeTruthy();
  });

  it(`should have as title 'angular-test'`, () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    expect(app.title).toEqual('angular-test');
  });

  it('should render title', () => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled = fixture.nativeElement as HTMLElement;
    expect(compiled.querySelector('.content span')?.textContent).toContain('angular-test app is running!');
  });
});
Using directives in our Angular app

Explanation

  • Lines 4–15: We create a component with a simple HTML template where names of books are printed, and the books that have the isRed property to be true are red. Others are green.
  • Lines 16–40: We create the AppComponent class which is called in the app.module.ts file. Inside this class, we declare a list containing different books, each with a name property and the isRed property.
Copyright ©2024 Educative, Inc. All rights reserved