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错误TypeError:无法读取未定义的属性'nativeElement'
我试图通过读者更改div的颜色,但无法更改它。模板ref nad视图子级访问div
答案 0 :(得分:0)
在调用ngAfterViewInit
回调之前设置视图查询。请检查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');
}
}