Angular - Material - First Field Focus

Angular – Material – Focus on first field when the form opens

I found a website that gave several ways to approach this. Here is what worked for me.

1
2
3
4
5
6
7
8
9
10
11
12
13
  <form [formGroup]="policyTypeCodeForm"  >
<mat-form-field class="full-width">
<input #txtCode
matInput
placeholder="Code"
formControlName="code"
required
autofocus="true">
<mat-error *ngIf="errorFormData?.Code">
{{errorFormData?.Code}}
</mat-error>
</mat-form-field>
:

In the first input textbox I added #txtCode. This is a control name.

Interesting parts of the code

1
2
3
4
5
6
7
8
import { Component, OnInit, ViewChild, ElementRef} from '@angular/core';

export class PolicyTypeCodeDetailsComponent implements OnInit {
@ViewChild("txtCode") txtCode: ElementRef;

ngAfterViewInit() {
this.txtCode.nativeElement.focus();
}

References