繁体   English   中英

如何在Angular中始终将焦点设置为输入

[英]How can I set focus always on input in Angular

我只想通过一个文本输入来控制我的应用程序,因此我需要始终关注它(以防止用户通过单击页面上的某处等而意外失去此焦点)。 公平地说,我什至不知道该怎么做。

我试图在此输入上使用html的自动对焦,然后检查它是否失去焦点。 但是我不知道如何“复兴”对此的关注。 这是我的代码:

HTML档案:

<div fxLayout fxLayoutAlign="center">
  <div fxFlex="80" class="operations">

    <div class="H-opt">Użytkownik: <span>{{ActualUser}}</span></div>
    <div class="H-opt">Magazyn źródłowy: <span></span></div>
    <div class="H-opt">Magazyn docelowy: <span></span></div>

    <input matInput [(ngModel)]="codeExec" (focusout)="reviveFocus()" (keyup.enter)="execAction($event.target.value)" autofocus >

  </div>

</div>

TS文件:

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../../shared/services/auth.service';
import { DatabaseService } from '../../../shared/services/database.service';
import { MatSnackBar, MatDialog } from '@angular/material';

@Component({
  selector: 'app-cbisgate-userdash',
  templateUrl: './cbisgate-userdash.component.html',
  styleUrls: ['./cbisgate-userdash.component.css']
})
export class CbisgateUserdashComponent implements OnInit {

  constructor(public dialog: MatDialog, private authService: AuthService, private databaseService: DatabaseService, public snackBar: MatSnackBar) { }

  codeExec: string = "";

  ActualUser;
  DepotFrom;
  DepotTo;

  clearCodeExec() {
    this.codeExec = "";
  }

  reviveFocus() {
    console.log("I'm trying to revive this input!");
  }

  execAction(code) {
    this.ActualUser = code;
    console.log(code);
    this.clearCodeExec();
  }

  ngOnInit() {
  }

}

我如何使用此reviveFocus函数,是否有任何方法可以再次关注此输入? 还是用另一种方式来“全天候”专注?

您应该改用(blur)事件绑定。 我认为当焦点事件模糊/丢失时,这是正确的绑定关键字。

首先,我们将blur事件绑定到onBlur()方法。 接下来,我们在输入元素上设置模板引用变量。

<input matInput #yourInput (blur)="onBlur($event)">

然后在您的component.ts上,我们将设置元素以使其在触发onBlur集中。

@ViewChild('yourInput', {static: false}) yourInput: ElementRef;

onBlur(event) {
  this.yourInput.nativeElement.focus()
}

我在这里做了一个演示。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM