TypeError:从服务创建动态组件时,无法读取 undefined 的属性(读取“clear”)

TypeError: Cannot read properties of undefined (reading 'clear'), when creating Dynamic component from service

提问人:Avo 提问时间:11/8/2023 更新时间:11/8/2023 访问量:12

问:

我创建了一个组件,它将呈现自定义小吃吧。我正在从服务进行调用并传递数据

 public success(
    message: string,
    wordsToTranslate?: TranslationParameter,
    translate: boolean = true
  ): void {
    const translateMessage = translate ? this.translateService.instant(message, wordsToTranslate) : message;
    this.dynamicComponent.showSnackbar(translateMessage, this.dismiss, 'bg-success');
  }

@Component({
  selector: 'app-dynamic-component',
  template: `<ng-container #container></ng-container>`,
})
export class DynamicComponent {
  @ViewChild('container') container: ViewContainerRef;

  constructor(
    private appRef: ApplicationRef,
  ) {}

  showSnackbar(translateMessage: string, dismiss: string, bgSuccess: string) {
    this.createDynamicComponent(translateMessage, dismiss, bgSuccess);
  }

  private createDynamicComponent(translateMessage: string, dismiss: string, className: string) {
    this.container.clear();
    const componentRef = this.container.createComponent(SnackbarComponent);
    componentRef.instance.message = translateMessage;
    componentRef.instance.className = dismiss;
    componentRef.instance.dismiss = className;

    // Attaches the view of the dynamic component to the Angular application's change detection system,
    this.appRef.attachView(componentRef.hostView);

    // Append the component to the DOM
    const domElement = (componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;
    document.body.appendChild(domElement);
  }
}

请为此提供解决方案,因为我的容器未定义!!

我期待建议,如何解决这个问题?

未定义 的角度动力学组件

评论


答: 暂无答案