I would like to create some small directive to check an input is focused or not in template rules. It's easy to use component with (focus) and (blur) events but this code will be in every form in the project. So it's good idea to create a directive.
Please pay attention to 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>
I know how to use HostListener to catch focus state changes But i don't know how to save this state in element so it's possible to use in a template.
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
}
}
At last but not the least is't possible to assign the directive for any input with type text or password by default?