如何在Angular 7中将孩子附加到div

时间:2019-02-20 15:47:28

标签: typescript angular7

我试图将一个子代添加到Angular 7中html中定义的div中,但不断抛出以下错误:

Cannot read property 'appendChild' of null

这是导致问题的代码

export class ProductComponent{
constructor(){ 
this.init
}
init(){
    //private container : any = document.createElement('div');
    this.container.className = 'shirt_Model_Div';
            const modelDiv = document.getElementById('shirtModelDiv');
            modelDiv.appendChild(this.container); //error occurs here
            this.renderer.setSize($(modelDiv).width(), $(modelDiv).height(), $(modelDiv).maxHeight);
}
  }

我的html:

<h1>3d Model Basic</h1>
<div id="shirtModelDiv" style="width: calc(100%);"></div>

也许我在错误的位置定义了代码?我对角度组件的生命周期不熟悉

1 个答案:

答案 0 :(得分:0)

在生成视图之前,将在组件的构造函数中调用您的代码。您需要在ngAfterViewInit()或更高版本中调用它

所以您可以像这样

ngAfterViewInit() {
    this.container.className = 'shirt_Model_Div';
    const modelDiv = document.getElementById('shirtModelDiv');
    modelDiv.appendChild(this.container); //error occurs here
    this.renderer.setSize($(modelDiv).width(), $(modelDiv).height(), $(modelDiv).maxHeight);
}

您需要对组件实施AfterViewInit

export class AnyComponent implements AfterViewInit {
...
}