Membuat Custom Directive – Part 1

Angular directive sudah dibahas pada modul Pengenalan Angular Directive, disana dibahas terdapat Built-in Directive seperti ngFor, ngIf, ngClass dan ngStyle.

Pada modul ini kita akan membahas membuat custom directive.

Skenarionya Directive yang kita buat akan mengubah warna background sebuah element.

Ya, betul itu dapat dilakukan dengan mudah melalui CSS atau menggunakan Built-in Directive. Skenario ini hanya digunakan untuk keperluan demo agar mudah memahami konsep dari custom directive.

Buat file baru basic-highlight.directive.ts (Anda bisa buat folder khusus untuk menyimpan file yang berhubungan dengan directive).

//import module yang diperlukan
import { Directive, ElementRef, OnInit } from "@angular/core";

//gunakan decorator @Directive
//selector digunakan sebagai attribute html
@Directive({
    selector: '[appBscHighlight]'
})
export class BasicHighlightDirective implements OnInit{
    constructor(private elRef: ElementRef){}

    ngOnInit(): void {
        //mengubah background color
        this.elRef.nativeElement.style.backgroundColor = "green";
    }
}

Kita perlu menambahkan informasi directive diatas pada app.module.

Buka file app.module.ts, kemudian tambahkan informasi directive.

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
//import custom directive
import { BasicHighlightDirective } from './basic-highlight.directive';

@NgModule({
  declarations: [
    AppComponent,
    BasicHighlightDirective  //import custom directive
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Directive sudah bisa kita gunakan. Buka file app.component.html, tambahkan kode dibawah.

Perhatian: directive digunakan sebagai HTML element attribute, karena pada saat membuat directive digunakan selector attribute.

<div class="container">
    <div class="row">
        <div class="col-xs-12">
            <p appBscHighlight>Custom Directive</p>
        </div>
    </div>
</div>

Sesuai ekspektasi, element paragraph akan ditampilkan dengan warna background hijau.

Sharing is caring:

1 thought on “Membuat Custom Directive – Part 1”

Leave a Comment