Friday, August 7, 2020

Creating Custom Directives in Angular 9/8

Angular 9/8 Custom Directives will be discussed here in this article. You can compare the building of directives with the building of components in Angular 2. As for components, they are directives with a view attached to it. In general, there are 3 types of directives: structural, attribute and components.

Directives in Angular 9/8


Angular 9/8 Custom Directives

We are going to import Renderer2, ElementRef and Directive from @angular/core. Then we will use the renderer to set the style of the element according to our need:

Run the following command to generate custom directive in Angular app.

ng generate directive roundBlock

round-block.directive.ts

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


@Directive({

  selector: '[appRoundBlock]'

})


export class RoundBlockDirective {

  constructor(renderer: Renderer2, elmRef: ElementRef) {

    renderer.setStyle(elmRef.nativeElement, 'border-radius', '100px');

  }

}

We have wrapped the selector in brackets: [appRoundBlock]. This is to turn it into a border-radius directive.

Now let’s check this out in our app module.

When we ran the command to create custom directives in an Angular app, that command automatically registered custom directive in app module file.

app.module.ts

import { BrowserModule } from '@angular/platform-browser';

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

import { AppComponent } from './app.component';

import { RoundBlockDirective } from './round-block.directive';

@NgModule({

  declarations: [

    AppComponent,

    RoundBlockDirective

  ],

  imports: [

    BrowserModule

  ],

  providers: [],

  bootstrap: [AppComponent]

})

export class AppModule { }

How to Use Custom Directive in our Angular Template?

We make use of the directive present in the template. We can easily use attribute directive in the template as we have shown below:

app.module.html

<div class="demo-block" appRoundBlock></div>

Markup

Set Up Dynamic Values in Angular 9/8 Custom Directives

Well, our appRoundBlock directive isn’t that smart. With the help of a style binding, we could have easily provided values to border-radius. Therefore, we are going to improve the directive by making it possible for us to pass values through to the directive.

round-block.directive.ts

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

@Directive({

  selector: '[appRoundBlock]'

})

export class RoundBlockDirective implements OnInit {

  @Input() appRoundBlock: string;

  constructor(

   private elmRef: ElementRef, 

   private renderer: Renderer2) 

  { }

  ngOnInit() {

    let roundVal = `${this.appRoundBlock}`;

    this.renderer.setStyle(this.elmRef.nativeElement, 'border-radius', roundVal);

  }

}

This is how we gain use it in html component:

app.component.html

<div class="demo-block" [appRoundBlock]="'30px'"></div>

No comments:

Post a Comment