I have this field in my reactive form which is present inside a matDialog
<mat-form-field
class="w-full"
*ngIf="formType == 'da_banker'"
>
<mat-select
value=""
(selectionChange)="
onTxnStatusChange($event.value)
"
formControlName="txn_status_banker"
name="txn_status_banker"
#setFocus
>
<mat-option value=""
>Select Transaction Status</mat-option
>
<mat-option
value="{{ row.value }}"
*ngFor="let row of txnUpdateOptions"
[ngClass]="
row.name == 'Pending'
? 'hidden'
: ''
"
>{{ row.name }}</mat-option
>
</mat-select>
<mat-error *ngIf="showTxnStatusError"
>Required</mat-error
>
</mat-form-field>
I am focusing this field when the view initializes using
@ViewChild('setFocus') setFocus:ElementRef;
ngAfterViewInit(): void {
this.setFocus['_elementRef'].nativeElement.focus();
}
it is working fine but when i submit the form i am not closing it as i have to fill it again for next data. For this, i want to focus the same field again and for this i am using this code after the submit button clicks
updateTxnStatus() {
if(this.form.invalid == true){
return;
}
this.setFocus['_elementRef'].nativeElement.focus();
console.log(this.setFocus['_focused']);
console.log(this.setFocus);
console.log(document.activeElement)
this.form.controls['txn_status_banker'].setValue('');
}
In console the active focused element is exactly what i want but in view it is not being focused.
Your focus() may fail if this.form.invalid is true or changes to the form clear the focus. Move .focus() the end of the block, make sure focus() is fired.