Detect Input Focus Using Angular 2+

WebTypescriptAngular

Web Problem Overview


I'm trying to create an auto-complete list that appears as you type, but disappears when you click elsewhere on the document. How do I detect that a form input is focused using Angular 2. Angular 1 has ng-focus, but I don't think Angular 2 supports that anymore.

<input id="search-box" type="search" class="form-control [(ngModel)]=query (keyup)=filter()>
    <div id="search-autocomplete" *ngIf="filteredList.length > 0">
        <ul *ngFor="#item of filteredList" >
            <li > <a (click)="select(item)">{{item}}</a> </li>
        </ul>
    </div>

By the way, I used this tutorial as guidance.

Web Solutions


Solution 1 - Web

There are focus and blur events:

<input (blur)="onBlur()" (focus)="onFocus()">

Solution 2 - Web

For those using @angular/material, you can get a reference to the MatInput instance which implements MatFormFieldControl interface exposing a nice focused property.

<mat-form-field>
  <input matInput #searchInput="matInput" type="text" />
  <mat-icon matPrefix svgIcon="filter" [color]="searchInput.focused ? 'primary' : ''"></mat-icon>
</mat-form-field>

Solution 3 - Web

You could also use FocusMonitor from @angular/cdk.

https://material.angular.io/guide/creating-a-custom-form-field-control#focused

focused = false;

constructor(fb: FormBuilder, private fm: FocusMonitor, private elRef: ElementRef<HTMLElement>) {
  ...
  fm.monitor(elRef.nativeElement, true).subscribe(origin => {
    this.focused = !!origin;
    this.stateChanges.next();
  });
}

ngOnDestroy() {
  ...
  this.fm.stopMonitoring(this.elRef.nativeElement);
}

Solution 4 - Web

You can use the ngControl directive to track change-state and validity of form fields.

<input type="text" ngControl="name" />

The NgControl directive updates the control with three classes that reflect the state.

State: Control has been visited

ng-touched
ng-untouched

State: Control's value has changed

ng-dirty
ng-pristine

State: Control's value is valid

ng- valid
ng- invalid

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionwpaktView Question on Stackoverflow
Solution 1 - WebkemskyView Answer on Stackoverflow
Solution 2 - WebamaredeumView Answer on Stackoverflow
Solution 3 - WebStanislav KarpovView Answer on Stackoverflow
Solution 4 - WebE. MuñozView Answer on Stackoverflow