繁体   English   中英

typescript子组件document.getElementById返回null

[英]typescript child component document.getElementById return null

我需要将elmarquez / threejs-viewcube中的“CubeView”添加到我的项目中。 我创建了组件。 组件代码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);
}
}

浏览器日志仅写入null。

我试图修改代码:

1)

const myElement: HTMLElement | null = document.getElementById('viewcube');

2)

constructor(@Inject(DOCUMENT) private document: Document){
}

但结果保持不变。

使用AfterViewInit代替构造函数之类的东西

export class CubeViewWebGlComponent implements OnInit,AfterViewInit  {
      ngAfterViewInit() {
        //get your element here
      }
....

您可以在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM