Skip to content

Provide better type safety for viewChild (and viewChildren) #59717

Closed as duplicate

Description

@StephenSPaul

Which @angular/* package(s) are relevant/related to the feature request?

core

Description

At the moment, it is easy to incorrectly type a viewChild() (or viewChildren()) signal. For example:

readonly myElement = viewChild<HTMLInputElement>('someSelector');

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

  1. added this to the needsTriage milestone on Jan 27, 2025
  2. JoostK commented on Feb 12, 2025

    @JoostK
    Member

    We're folding this one into the existing #43253 as a tracking issue for type-checking view queries.

  3. angular-automatic-lock-bot commented on Mar 15, 2025

    @angular-automatic-lock-bot

    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.

  4. locked and limited conversation to collaborators on Mar 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions