Hi,
I improved the solution by suspending the focus setting until the view has
been refreshed:
ngAfterViewChecked() {
if (this.setFocus && this.input) {
this.renderer.invokeElementMethod(this.input.nativeElement, 'focus');
this.setFocus = false;
}
}
...
public show(): void {
this.setVisible(true);
this.setFocus = true;
}
This works as expected and focusing is now done by the component and not the
view.
However, I'm still not sure whether this is the bset solution since registering
the lifecycle hook seems quite costly to me.
Regards,
Björn
Am Mittwoch, 3. Mai 2017 17:45:56 UTC+2 schrieb Björn Peemöller:
>
> 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
>
--
You received this message because you are subscribed to the Google Groups
"Angular and AngularJS discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.