I have a form which is only visible when a button is clicked. I want the user to click the button and have the focus placed on the first input field once the form is displayed.
Using @Viewchild I can't do this because the form is not available when the component first loads. I get the error Cannot read property 'nativeElement' of undefined
TS
formLoaded = false;
@ViewChild("firstName") nameField: ElementRef;
editName(): void {
this.formLoaded = true;
this.nameField.nativeElement.focus();
}
HTML
<button mat-raised-button color="primary" (click)="editName()">Edit</button>
<div *ngIf="formLoaded" class="group">
<mat-form-field>
<input #firstName matInput>
</mat-form-field>
</div>
How can I access the input #firstName so I can give it focus?
A simplified version of my actual code is here.
Make use of the AfterViewChecked lifecycle hook, it is run everytime change detection is triggered. Thereby, only after the form is present on the template will you set focus for it.
ngAfterViewChecked() {
if (this.formLoaded) {
this.nameField.nativeElement.focus();
}
}
Remove the focus statement from the editName method:
@ViewChild("firstName") nameField: ElementRef;
editName(): void {
this.formLoaded = true;
}