Build A Custom Attribute Directive
* Attribute Directives listens & modifies a behavior of html
elements, properties, attributes & components.
Building A Custom Directive
* An attribute
Directives minimally requires a controller class which is decorated with ‘@Directive’,
which specifies a selector to be used with element to change its behavior.
* In this tutorial, we
will be creating a directive which will highlight and bold the text on applied
HTML element.
* Run the cmd ng
generate directive elementhighlighter or ng g d
elementhighlighter to create a directive.
Apply The Directive
To Element
* To apply the directive,
we have created to an element use the selector.
app.component.ts
<div>
<div appElementHighlighter>This tutorial elaborates custom directive</div>
</div>
elementhighlighter.directive.ts
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appElementHighlighter]'
})
export class ElementHighlighterDirective {
constructor(er: ElementRef) {
er.nativeElement.style.backgroundColor = 'yellow';
er.nativeElement.style.fontWeight = 'bold';
}
}
* Imports Directive namespace to avail @Directive decorator which makes a controller to behave as directive.
* Also we imports ElementRef
from ‘@angular/core’ library which inject the DOM element to host on which the directive
going to be applied.
* ElementRef grants
direct access to DOM element using its nativeElement property.
app.component.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {ElementHighlighterDirective} from './Directives/Attribute/elementhighlighter.directive';
@NgModule({
declarations: [
AppComponent,
ElementHighlighterDirective
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
No comments:
Post a Comment