04 November 2018

Cách sử dụng Directives trong Angular 2+

1. Directive Attribute.

Bước 1: Tạo project Angular 2 bấm vào đây

Bước 2: Tạo directive có tên là highlight

ng generate directive highlight
src/app/app.component.html
Angular 2
<h1>My First Attribute Directive</h1>
<p myHighlight>Highlight me!</p>
src/app/highlight.directive.ts
Angular 2
import {
    Directive,
    ElementRef,
    Input
} from '@angular/core';
@Directive({
    selector: '[myHighlight]'
})
export class HighlightDirective {
    constructor(el: ElementRef) {
        el.nativeElement.style.backgroundColor = 'yellow';
    }
}

Result
eee
Directives sử dụng event
src/app/highlight.directive.ts (constructor)
Angular 2
constructor(private el: ElementRef) { }

src/app/highlight.directive.ts
Angular 2
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
  selector: '[myHighlight]'
})
export class HighlightDirective {
  constructor(private el: ElementRef) { }
  @HostListener('mouseenter') onMouseEnter() {
    this.highlight('yellow');
  }
  @HostListener('mouseleave') onMouseLeave() {
    this.highlight(null);
  }
  private highlight(color: string) {
    this.el.nativeElement.style.backgroundColor = color;
  }
}
Result
2. Directive @Input data binding

src/app/app.component.html
Angular 2
<span [appHighlight]="'red'">Hello Directive @Input..</span>

src/app/highlight.directive.ts
Angular 2
import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({
  selector: '[myHighlight]'
})
export class HighlightDirective {

  constructor(private el: ElementRef) { }

  @Input('myHighlight') highlightColor: string;

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

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

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

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang