首页 > 解决方案 > Render is not able to changed the color of back ground

问题描述

export class ParentComponent implements OnInit {

  constructor(private render : Renderer2) { }

  @ViewChild('box', { static: false }) box: ElementRef;

  ngOnInit(): void {

    this.render.setStyle(this.box.nativeElement,'backgroundColor','red');  }

}


<div #box>

    <p > from rendere</p>

</div>

core.js:6228 ERROR TypeError: Cannot read property 'nativeElement' of undefined

I am trying to change the colour of div by reader following is not able to change it. accessing the div by the template ref nad view child

标签: angulartypescript

解决方案


View queries are set before the ngAfterViewInit callback is called. Check please link

export class ParentComponent implements OnInit,AfterViewInit{        
    constructor(private render : Renderer2) { }        
    @ViewChild('box', { static: false }) box: ElementRef;
    ngOnInit(): void {}
    ngAfterViewInit(){
        this.render.setStyle(this.box.nativeElement,'backgroundColor','red');       
    }  
}

推荐阅读