[Angular]实现Trim指令

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

@Directive({
  selector: '[trim]'
})
export class TrimDirective {
  constructor(private elementRef: ElementRef, private control?: NgControl) { }

  @HostListener('blur', ['$event.target'])
  onBlur(event) {
    console.log("==========trim操作==========");
    if (event.value) {
      if (this.control) {
        this.control.control.patchValue(this.control.value.trim());
        this.control.control.updateValueAndValidity();
      }
      else {
        this.elementRef.nativeElement.value = event.value.trim();
      }
    }
  }
}

 

你可能感兴趣的:(Angular)