Compiled with problems: × ERROR - error TS2532: Object is possibly 'undefined'

21 Views Asked by At

I want to use nativeElement in ngOnInit but i can't able to use in lifecycle. It throws an error.

import { Directive, ElementRef, OnInit } from "@angular/core";

@Directive({
    selector: '\[setBackground\]'
})
export class SetBackgroundDirective implements OnInit {
    private element: ElementRef | undefined;
    constructor(element: ElementRef) {
        this.element = element;
    }
    ngOnInit() {
        this.element.nativeElement.style.backgroundColor = 'green';
    }

}
0

There are 0 best solutions below