You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 15:05:55