4

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?

1 Answer 1

2
@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);
  }
}

This directive allows two ways of using the hasFocus value

  • referencing the directive
<input focused #isFocused="hasFocus">
<div>has focus: {{isFocused.hasFocus}}</div>
  • binding to the event
<input focused (focusChange)="isFocused = $event">
<div>has focus: {{isFocused}}</div>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.