简体   繁体   中英

typescript child component document.getElementById return null

I need add "CubeView" from elmarquez/threejs-viewcube to my project. I created component. A component code 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.

I tried to modify the code:

1)

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

2)

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

But the result remained the same.

Use AfterViewInit instead of constructor something like

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

///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);
      }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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