Angular 17.2中如何为viewChild指定ElementRef特定泛型?
Angular 17.2 为 viewChild 的 ElementRef 指定正确泛型的方法
要让viewChild返回Signal<ElementRef<MatCard> | undefined>类型的信号,你可以通过显式指定泛型参数解决,有两种可选写法:
写法一:同时指定 viewChild 和 ElementRef 的泛型
matCardElt = viewChild<ElementRef<MatCard>>(MatCard, { read: ElementRef<MatCard> });
写法二:仅指定 viewChild 的泛型(简化版)
matCardElt = viewChild<ElementRef<MatCard>>(MatCard, { read: ElementRef });
两种写法都能让返回的信号类型符合预期。原代码中类型被推断为ElementRef<any>,是因为Angular默认无法自动推导ElementRef的泛型参数,显式指定后就能锁定为MatCard类型。
内容的提问来源于stack exchange,提问作者Matthieu Riegler
相关产品推荐
相关产品推荐

