Angular 2 个带有属性指令的自定义状态

Angular 2 custom state with attribute directive

我想创建一些小指令来检查模板规则中是否聚焦输入。 将组件与 (focus) 和 (blur) 事件一起使用很容易,但是此代码将以项目中的每种形式出现。所以创建一个指令是个好主意。

请关注somefield.focused

<div class="form-group" [ngClass]="{'error': !somefield.valid && !somefield.focused }">
  <div class="controls">
    <input type="text" class="form-control" name="somefield" [(ngModel)]="model.somefield" #somefield="ngModel" required minlength="5" maxlength="15" />
    <div class="error-block" *ngIf="!somefield.valid && somefield.errors?">Some error occurred</div>
  </div>
</div>

我知道如何使用 HostListener 捕捉焦点状态变化 但是我不知道如何在元素中保存这个状态,所以可以在模板中使用。

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

@Directive({
  selector: 'input[focused]'
})

export class FocusedDirective {

  constructor(private el: ElementRef) {
    // TODO: set focused to false
  }

  @HostListener('blur', ['$event'])
  onBlur(e) {
    // TODO: set focused to false
  }

  @HostListener('focus', ['$event'])
  onFocus(e) {
    // TODO: set focused to true
  }

}

最后但并非最不重要的一点是,默认情况下无法为任何类型为文本或密码的输入分配指令?

@Directive({
  selector: 'input[focused]',
  exportAs: 'hasFocus'
})

export class FocusedDirective {

  hasFocus:boolean = false;
  focusChange:EventEmitter<boolean> = new EventEmitter<boolean>();

  constructor(private el: ElementRef) {}

  @HostListener('blur', ['$event'])
  onBlur(e) {
    this.hasFocus = false;
    this.focusChange.emit(this.hasFocus);
  }

  @HostListener('focus', ['$event'])
  onFocus(e) {
    this.hasFocus = true;
    this.focusChange.emit(this.hasFocus);
  }
}

此指令允许使用两种方式使用 hasFocus

  • 引用指令
<input focused #isFocused="hasFocus">
<div>has focus: {{isFocused.hasFocus}}</div>
  • 绑定到事件
<input focused (focusChange)="isFocused = $event">
<div>has focus: {{isFocused}}</div>