I am trying to assign styles to an element, I have tried to use the @ViewChild decorator, but when compiling I get an error:Property #element# has no initializer and is not definitely assigned in constructor.
The idea is to access the element as it has always been done with JavaScript ( document.getElementById(#elemento).style...
), however this practice is discouraged and I have looked at other ways, in other articles they refer to the Renderer2 class, which is the best way to work with the DOM.
I leave the code here for you to take a look, to see if you find the error:
HTML
<div #roompanel...
ST
import { Component, ElementRef, OnInit, Renderer2, ViewChild } from '@angular/core';
...
export class CastComponent implements OnInit {
@ViewChild("roompanel") roompanel: ElementRef;
...
constructor (private renderer:Renderer2) {
}
showpanel(){
this.renderer.setStyle(this.roompanel.nativeElement, 'display', 'flex');
}
}
Here is a screenshot of the exact error.
In some forums they indicate that placing ! after roompanel it fixes the problem, and it's true, but it doesn't give me peace of mind because I don't know what exactly it's doing.
I think it goes without saying that I am very new to Angular and still learning.
The message
Property has no initializer and is not definitely assigned in the constructor
can appear when adding some configuration in the tsconfig.json file to have an Angular project compiled in strict mode.That causes the compiler to raise an error if a variable has not been initialized before it is used. To avoid that compile error you can use a typescript feature called Definite Assignment Assertions where you use the operator
!
at the end of the variable name to assure the compiler that the variable will be given a value before it is used.