我想创建一些小的指令来检查输入是否集中在模板规则中。带有(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
}
}
最后但并非最不重要的是,默认情况下是否无法为任何类型为text或password的输入分配指令?
@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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句