【问题标题】:Dom element not found in lazy loaded angular component在延迟加载的角度组件中找不到 Dom 元素
【发布时间】:2021-03-22 09:12:20
【问题描述】:

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

发生延迟加载的Stepper组件:

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 和 ngAfterViewChecked(如上所示)。我尝试将元素分配给 Viewchild 并更改该 viewchild 的样式。

【问题讨论】:

    标签: angular typescript lazy-loading nebular


    【解决方案1】:

    尝试使用 #ref 代替 id 来使用 Viewchild

    类似

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

    在你的 ts 文件中:

    @ViewChild("ref") ref;
    

    然后,在里面调用 ngAfterViewInit 喜欢this.ref.nativeElement.textContent

    【讨论】:

    • 感谢您的回答。不幸的是我得到了同样的错误。我相信 nebular 如何处理其步进器内容会导致 afterviewchecked 在容器存在之前运行,这很奇怪。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-22
    • 2015-07-01
    • 1970-01-01
    相关资源
    最近更新 更多