简体   繁体   中英

How can I set focus always on input in Angular

I want to control my application JUST from one text input, so I need to have focus ALWAYS on it (to prevent users from accidentally losing this focus by clicking somewhere on page etc.). And to be fair I don't even know how can I do this.

I tried to use html's autofocus on this input and then check if it loses it's focus. But I don't know, how to "revive" this focus on it. This is my code:

HTML file:

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

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() {
  }

}

How can I use this reviveFocus function, is there any way to make focus again on this input? Or it's other way to do the "all-time" focus?

You should use the (blur) event binding instead. I think that is the right binding keyword when it comes to blurred/losing focus events.

First, we bind the blur event to the onBlur() method. Next, we set an template reference variable on the input element.

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

And on your component.ts, we will set the element to focus whenever onBlur is triggered.

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

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

I have made a demo over here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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