在延迟加载的角度组件中找不到Dom元素



我有一个星云步进器组件,在最后一步,我延迟加载该组件。在那个组件中,我需要通过id来识别一个元素,并对其进行更改

发生延迟加载的步进器组件:

Html-

<nb-step [label]="labelFour">
<ng-template #labelFour>Fourth step</ng-template>
<h3>Edit Your Image</h3>

<div class="container step-container">
<ng-template #canvasContainer ></ng-template>


</div>

<button nbButton nbStepperPrevious>prev</button>
<button nbButton nbStepperNext>next</button>
</nb-step>

TS-

@ViewChild('canvasContainer', {read: ViewContainerRef}) canvasContainer: ViewContainerRef;
canvasInitialized = false;
async createCanvas() {
await this.lazyLoadCanvas();
this.canvasInitialized = true;

}
private async lazyLoadCanvas() {
const {CanvasComponent} = await import('../../single/canvas/canvas.component');
const canvasFactory = this.cfr.resolveComponentFactory(CanvasComponent);
const {instance} = this.canvasContainer.createComponent(canvasFactory, null, this.injector);

}
noDesignSelected:boolean;
thirdStepNext(){           //Third step is clicked

if(this.postDesignService.designID != -1){
this.stepper.next();
this.noDesignSelected = false;
this.createCanvas();
} else {
this.noDesignSelected = true;
}

}

加载在中的组件

Html-

<div class="canvas-bg">
<div id="container" ></div>
</div>

TS-

ngAfterViewChecked() {
document.getElementById('container').classList.add('test');   //error here
this.stage = new Konva.Stage({
container: 'container',            //error here
width: this.stageWidth,
height: this.stageHeight,
});
}

错误告诉我找不到id为"container"的元素。

我已经尝试过ngOninit、ngAfterViewInit和ngAfterView Checked(如上所示(。我已经尝试将元素分配给Viewchild并更改该Viewchild的样式。

尝试使用Viewchild使用#ref而不是id

类似的东西

<div class="canvas-bg">
<div *#ref* id="container" ></div>
</div>

在您的ts文件中:

@ViewChild("ref") ref;

然后打电话进去ngAfterViewInit类似this.ref.nativeElement.textContent

最新更新