I am currently facing an issue where I need to focus on a specific input in my code based on certain conditions derived from an observable. In this scenario, I have initialized a boolean to true
inside the ngOnInit()
method.
export class InputOverviewExample implements OnInit {
bool: boolean;
@ViewChild("input1", { static: true }) input1: MatInput;
@ViewChild("input2", { static: true }) input2: MatInput;
ngOnInit() {
this.bool = true;
this.input1.nativeElement.focus();
this.input2.nativeElement.focus();
}
}
However, I have observed that the focus functionality does not work as expected when using a mat-form-field
that is conditionally displayed.
<form class="example-form">
<h3>Without *ngIf :</h3>
<mat-form-field appearance="outline" class="example-full-width">
<input matInput #input1 placeholder="Auto focus" value="Test_input1" />
</mat-form-field>
<h3>With *ngIf :</h3>
<mat-form-field appearance="outline" class="example-full-width" *ngIf="bool">
<input matInput #input2 placeholder="Auto focus" value="Test_input2" />
</mat-form-field>
</form>
Link to interactive code example on StackBlitz
If anyone has a solution to this issue, I would greatly appreciate it.
Thank you.