0

I want to get a HTML element with DOM manipulation. When I try to get the element with ViewChild, it gives the following error. When I click the quick fix, it adds | undefined. But this time I can not call the variable as this.map

Property 'map' has no initializer and is not definitely assigned in the constructor.

import { Component, ElementRef, OnInit, ViewChild, AfterViewInit } from '@angular/core';
export class SlideComponent implements OnInit, AfterViewInit{

  @ViewChild('el', { static: true}) map: ElementRef;

  constructor() { 
  }

  ngOnInit(): void {
  }
  ngAfterViewInit(){
    console.log(this.map.nativeElement);
  }
}

html element

<div class="carousel_track_container" #el></div>

A7x
  • 383
  • 3
  • 15
  • https://stackoverflow.com/questions/49699067/property-has-no-initializer-and-is-not-definitely-assigned-in-the-construc – Ihor Yanovchyk Sep 29 '21 at 22:06
  • thanks, I set the "strictPropertyInitialization": false. But in this case, I don't see the following instead of HTML Element. div.carousel_track_container accessKey: "" align: "" ariaAtomic: null ariaAutoComplete: null ariaBusy: null ariaChecked: null ariaColCount: null ariaColIndex: null ariaColSpan: null ... – A7x Sep 29 '21 at 22:21

1 Answers1

1

This happens when you use Angular's strict mode. It becomes very cautious that you don't run into errors by making sure you declare your variables properly.

In other words, if you add a variable that's global to the class, you either have to set it in the constructor or add undefined as a possible return type. This is because if you don't set it in the constructor, there is a chance you won't set it at all.

Option 1: You're not sure if you're going to need to use it:

@ViewChild('el', { static: true}) map: ElementRef | undefined;

Option 2: Set the variable in the constructor

Note: Since you're using ViewChild, it won't exist yet so you could only set it to undefined.

@ViewChild('el', { static: true}) map: ElementRef;

  constructor() { 
      this.map = undefined;
  }
cattourist
  • 209
  • 2
  • 5
  • 2
    you can shorthand the declaration in option 1 a little... `@ViewChild('el', { static: true}) map?: ElementRef;` – bryan60 Sep 29 '21 at 23:52
  • Yes @bryan60!! I've switched to declaring my variables that way as well. If you're not sure the variable will be used, add a question mark: el?: ElementRef; If it's definitely going to be used, add an exclamation mark: el!: ElementRef; – cattourist Jan 26 '23 at 03:18