Reputation: 1338
I´m currently trying to set the cursors focus on a specific input field, which is just displayed when the surrounding ngIf is true.
The html code looks something like this:
<div>
<button (click)="showFirst = !showFirst">Toogle</button>
<div *ngIf="showFirst">
<!-- Some content -->
</div>
<div *ngIf="!showFirst">
<input type="text" #myInput>
</div>
</div>
In my components JS I´m trying to get the ElementRef but it returns undefined
all the time because I try to fetch it before it was initialized.
So the qustion is:
How is it possible to set the focus on the input field after showFirst
becomes false
and the input gets visible?
Upvotes: 3
Views: 2100
Reputation: 73761
You can set the focus in the AfterViewChecked
lifecycle hook, as shown in this plunker. I added a check to make sure that the focus is set only when the input element becomes visible, not every time AfterViewChecked
is triggered.
import { Component, ViewChild, AfterViewChecked, ElementRef } from '@angular/core';
export class MyComponent implements AfterViewChecked {
@ViewChild("myInput") private myInput: ElementRef;
public showFirst = true;
private prevShowFirst = true;
public ngAfterViewChecked(): void {
if (!this.showFirst && this.prevShowFirst) {
this.myInput.nativeElement.focus();
}
this.prevShowFirst = this.showFirst;
}
}
Upvotes: 3
Reputation: 278
Angular has a lifecycle hook ngAfterViewChecked
which is called after every check of a component's view.
Once your view is changed this lifecycle hook will be called and here you can write the logic for focusing.
ngAfterViewChecked(){
// you logic for focusing or check ElementRef.
}
Upvotes: 0
Reputation: 2274
You can try to get the ElementRef inside the OnChanges life cycle hook. Something like:
OnChanges(): void {
if (!this.showFirst) {
// check ElementRef
}
}
Upvotes: 0
Reputation:
You can use the autofocus attribute. Or just add a setFocus at the end of (click) if showFirst is false
Upvotes: 0