Hi Sander,
thank you for your reply! This is what I initially, I called
@ViewChild('usernameField') input : ElementRef;
...
public show(): void {
this.setVisible(true);
this.input.nativeElement.focus();
}
where the field is provided by the template:
<input #usernameField
type="text"
class="form-control"
id="username"
name="username"
...>
<button (click)="show()">Switch User</button>
However, I receive the error
TypeError: Cannot read property 'nativeElement' of undefined
I guess this is caused by the following constellation: The ViewChild is injected at component creation, but since the input element is intially hidden (using *ngIf), it is not created and thus not injected. If the component is later changed to be visible, then the input is created but the ViewChild reference is not injected anymore. Furthermore, if I hide the component, the input is also removed from the DOM, invalidating the reference.
Regards,
Björn