You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Provide better type safety for viewChild (and viewChildren) #59717
Here I am passing a generic argument, HTMLInputElement, but the element may have a different type. Often I forget to wrap the element within an ElementRef, as I did here, but I digress. The point is, I often waste time being unsure of what is actually being injected by Angular in the component class.
Proposed solution
I believe that the easiest solution would be to include some kind of validator function:
readonly myElement = viewChild('someSelector', { validator: e => e instanceof HTMLInputElement });
Type signature would be as follows:
<T>(selector: string, options: { validator: (el: unknown) => el is T }) : Signal<T>;
Alternatives considered
Alternative 1:
The current API is not as ergonomic as it could be. Why can't the Angular Language service ensure that myElement is of the correct type:
readonly myElement: HTMLElement;
... and in the template:
<input #myElement /> <!-- throw error here (if not of type HTMLElement) -->
Alternative 2:
I thought about creating an external utility function that wraps the existing functionality but does an additional type check when the signal is invoked. I was unsuccessful. Perhaps you could tell me how to facilitate this. Or better, yet, perhaps you could build a function that facilitates this.
Activity
JoostK commentedon Feb 12, 2025
We're folding this one into the existing #43253 as a tracking issue for type-checking view queries.
ViewChild/ContentChildand through DI #43253angular-automatic-lock-bot commentedon Mar 15, 2025
This issue has been automatically locked due to inactivity.
Please file a new issue if you are encountering a similar or related problem.
Read more about our automatic conversation locking policy.
This action has been performed automatically by a bot.