Reputation: 367
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?
Upvotes: 3
Views: 16287
Reputation: 42576
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.
Upvotes: 4