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

时间:2017-01-16 11:21:33

标签: angular directive

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

请注意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
  }

}

最后但是至少不可能默认为任何带有文本或密码类型的输入分配指令吗?

1 个答案:

答案 0 :(得分:1)

@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>