reboottime / Angular-Playbook

Crash angular for interview, now it's a repository works as a Angular playbook.
2 stars 0 forks source link

[Angular Fundamental] Build Angular Directives #29

Open reboottime opened 7 months ago

reboottime commented 7 months ago

Overview

This article discusses Angular directives, covering:


References

reboottime commented 7 months ago

What is Angular Directive

Usage and classifications

Directive is an instruction to the DOM, we use directive to


With angular directives, we can encapsulate reusable behaviors— directives can apply attributes, CSS classes, and event listeners to an element.



Angular Directive Types

image

structural directives are applied they generally are prefixed by an asterisk, , such as ngIf


reboottime commented 7 months ago

How to build Angular directives

Attribute directive

A step by step guide on building a highlight directive.

Angular supports generate directive using cli, bellow is the command to generate a directvi

sh ng generate directive highlight


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

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  @Input() highlightColor: string = 'yellow';

  constructor(private el: ElementRef) {}

  @HostListener('mouseenter') onMouseEnter() {
    this.highlight(this.highlightColor || 'yellow');
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.highlight(null);
  }

  private highlight(color: string | null) {
    this.el.nativeElement.style.backgroundColor = color;
  }
}


After importing the directive at the AppModule, you can utilize it everywhere inside of the app


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

import { AppComponent } from './app.component';
import { HighlightDirective } from './highlight.directive';

@NgModule({
  declarations: [
    AppComponent,
    HighlightDirective // Add the directive here
  ],
  imports: [BrowserModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}


<div [appHighlight]="'cyan'">
  Hover over me to highlight in cyan.
</div>
<div [appHighlight]="'pink'">
  Hover over me to highlight in pink.
</div>
reboottime commented 7 months ago

How to build Angular directives

Structure directive

reboottime commented 7 months ago

References