【问题标题】:Detect Input Focus Using Angular 2+使用 Angular 2+ 检测输入焦点
【发布时间】:2016-08-13 19:22:12
【问题描述】:

我正在尝试创建一个自动完成列表,该列表会在您键入时显示,但在您单击文档的其他位置时会消失。如何使用 Angular 2 检测表单输入是否聚焦。Angular 1 具有 ng-focus,但我认为 Angular 2 不再支持。

<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>

顺便说一句,我用这个教程是guidance

【问题讨论】:

    标签: web typescript angular


    【解决方案1】:

    focusblur事件:

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

    【讨论】:

      【解决方案2】:

      您可以使用 ngControl 指令来跟踪表单字段的更改状态和有效性。

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

      NgControl 指令使用三个反映状态的类更新控件。

      状态:控件已被访问

      ng-touched
      ng-untouched
      

      状态:控件的值已更改

      ng-dirty
      ng-pristine
      

      状态:控件的值是有效的

      ng- valid
      ng- invalid
      

      【讨论】:

      • 有帮助,但似乎没有提供焦点状态。
      • 有帮助,但问题是集中状态。 FormControl 没有明确提供聚焦状态。
      【解决方案3】:

      对于那些使用@angular/material 的人,您可以获得对MatInput 实例的引用,该实例实现了MatFormFieldControl 接口,公开了一个很好的focused 属性。

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

      【讨论】:

      • 很可爱!很高兴知道我们可以像这样动态更改显示。
      【解决方案4】:

      您也可以使用来自 @angular/cdk 的 FocusMonitor。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-16
        • 2019-03-24
        • 1970-01-01
        • 1970-01-01
        • 2017-03-18
        • 1970-01-01
        • 1970-01-01
        • 2010-09-26
        相关资源
        最近更新 更多