Detect Input Focus Using Angular 2+

后端 未结 4 752
Happy的楠姐
Happy的楠姐 2020-12-24 10:23

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 u

相关标签:
4条回答
  • 2020-12-24 10:55

    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
    
    0 讨论(0)
  • 2020-12-24 11:05

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

    0 讨论(0)
  • 2020-12-24 11:10

    There are focus and blur events:

    <input (blur)="onBlur()" (focus)="onFocus()">
    
    0 讨论(0)
  • 2020-12-24 11:15

    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>
    
    0 讨论(0)
提交回复
热议问题