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

38 Views Asked by At

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> ?

1

There are 1 best solutions below

0
Matthieu Riegler On BEST ANSWER

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 });