angularviewchild

Property 'divElem' has no initializer and is not definitely assigned in the constructor when using Template Reference Variable in 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

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


Solution

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

    You have 2 solutions.