4

I have created a simple application in angular using angular material library in which, I have used dialog component. When dialog is opened by user, it will have stepper component of angular material. It has 3 steps. Every steps has angular reactive forms. Problem that I am facing is that when user open dialog focus is directly done on stepper header's first step. I want to have focus on first form control of reactive form in first step.

<mat-form-field class="name">
<input
  matInput
  formControlName="description"
  #name
/>
</mat-form-field>

In component.ts file, I have written

@ViewChild('name', { static: true, read: ElementRef }) name: ElementRef;

and in ngAfterViewInit method, I have called focus method on name variable like:

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

It works, but output from this I am getting is like it first focus on FormControl and then again, move focus to stepper header's first step. How I should prevent focus from stepper header's first step and keep focus on first FormControl ?

JAYDIP HIRAPARA
  • 297
  • 4
  • 18
  • Guess: [`stopPropagation`](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation) but provide stackblitz demo if that doesn't work! – Prashant Pimpale Jan 17 '20 at 05:39

1 Answers1

1

Use this directive on the element, where the initial focus is expected: cdkFocusInitial, if this not enough take a look here.

Anarno
  • 1,470
  • 9
  • 18