[英]typescript child component document.getElementById return null
I need add "CubeView" from elmarquez/threejs-viewcube to my project. 我需要将elmarquez / threejs-viewcube中的“CubeView”添加到我的项目中。 I created component.
我创建了组件。 A component code abow:
组件代码abow:
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { DOCUMENT } from '@angular/common';
declare let THREE: any;
@Component({
selector: 'app-cube-view-web-gl',
template: '<div id="viewcube"> </div>',
styleUrls: ['./cube-view-web-gl.component.scss']
})
export class CubeViewWebGlComponent implements OnInit {
private domElement: any;
private renderer: any;
private scene : any;
ngOnInit() {
}
constructor() {
this.domElement = document.getElementById('viewcube');
console.log(myElement);
}
}
Browser log is writed only null. 浏览器日志仅写入null。
I tried to modify the code: 我试图修改代码:
1) 1)
const myElement: HTMLElement | null = document.getElementById('viewcube');
2) 2)
constructor(@Inject(DOCUMENT) private document: Document){
}
But the result remained the same. 但结果保持不变。
Use AfterViewInit instead of constructor something like 使用AfterViewInit代替构造函数之类的东西
export class CubeViewWebGlComponent implements OnInit,AfterViewInit {
ngAfterViewInit() {
//get your element here
}
....
you can use inside a Oninit or if you want inside the constructor you should use set time out like this 您可以在Oninit中使用,或者如果您想在构造函数中使用,则应该像这样使用set time out
///for constructor
Ele:any;
constructor(){
setTimeout(()=>{
this.Ele=document.getElementById('test');
console.log(this.Ele);
},100)
}
////for OnInit
ngOnInit(){
this.Ele=document.getElementById('test');
console.log(this.Ele);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.