Property 'divElem' has no initializer and is not definitely assigned in the constructor when using Template Reference Variable in V16

huangapple go评论70阅读模式
英文:

Property 'divElem' has no initializer and is not definitely assigned in the constructor when using Template Reference Variable in V16

问题

这是我的div元素,我想通过模板引用变量来访问这个元素,但我遇到了问题,它报错了。

这是我的div元素
<div (click)="settingUpItemsAnimations()" class="browse-shops-item" #browseShopItems></div>

这是我在组件类中读取该元素的方式
@ViewChild('browseShopItems', { read: ElementRef }) divElem: ElementRef;

我遇到了这个错误,不知道为什么在V16中不起作用
Property 'divElem' has no initializer and is not definitely assigned in the constructor.ts(2564)
(property) Tab2Page.divElem: ElementRef<any>

我尝试在V10中检查,它可以工作,但不知道为什么在V16中不起作用。

英文:

I have an div element in template and wanted to access the element by template reference variable.But i was facing the issue, it throws some error.

This is my div element
&lt;div (click)=&quot;settingUpItemsAnimations()&quot; class=&quot;browse-shops-item&quot; #browseShopItems&gt;&lt;/div&gt;

This is is how i was reading the that element in my component class
@ViewChild(&#39;browseShopItems&#39;, { read: ElementRef }) divElem: ElementRef;

I was getting this error, don't know why this is not working in V16
Property 'divElem' has no initializer and is not definitely assigned in the constructor.ts(2564)
(property) Tab2Page.divElem: ElementRef<any>

i tried checking in V10 it was working but no idea why is it not working in V16

答案1

得分: 0

因为在构造函数中未定义 divElem,所以编译器会因为 strictPropertyInitialization 规则而报错。

你有两个解决方案。

  • 将属性设为可选:divElem?: ElementRef
  • 使用非空断言:divElem!: ElementRef
英文:

Since divElem is not defined in the constructor so the compiler will complain because of the strictPropertyInitialization rule.

You have 2 solutions.

  • Make the property optional : divElem?: ElementRef
  • Use the non-null assertion : divElem!: ElementRef

huangapple
  • 本文由 发表于 2023年7月3日 15:16:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76602598.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定