Search code examples
angularangular-signals

How can I type my viewChild to return a specifed `ElementRef` generic:


With v17.2, when I use the new signal queries like viewChild(), I can access the ElementRef with :

matCardElt = viewChild(MatCard, { read: ElementRef });

But this returns a Signal<ElementRef<any> | undefined> instead of Signal<ElementRef<MatCard> | undefined>

How can I enforce the right generic for ElementRef, so I can get a <ElementRef<MatCard> ?


Solution

  • This is currently a known limitation of the signal queries (inject has the same issue)

    To returned the right generic type, you need to specify it yourself.

    The signal query is defined as

    <LocatorT, ReadT>(locator: ProviderToken<LocatorT> | string, opts: {
        read: ProviderToken<ReadT>;
    }): Signal<ReadT | undefined>;
    

    You need to specify LocatorT and ReadT, so in our case this would be:

    matCardEl = viewChild<MatCard, ElementRef<MatCard>>(MatCard, { read: ElementRef });