英文:
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
<div (click)="settingUpItemsAnimations()" class="browse-shops-item" #browseShopItems></div>
This is is how i was reading the that element in my component class
@ViewChild('browseShopItems', { 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论