I have created a component that will render custom snack bar . I am doing the call from service and passing data

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

Please provide solution for this, as my container is undefined!!

I am expecting suggestions, how to resolve this ?

0

There are 0 answers