Search code examples
angularangular-dynamic-components

Outputs on dynamic components without view


On an Angular 8 project i created some dynmic components without a viewref with the following code:

const componentFactory = this.componentFactoryResolver.resolveComponentFactory(HelloComponent);
const componentRef = componentFactory.create(this.injector);      
componentRef.changeDetectorRef.detectChanges();    
componentRef.instance.slideContentRendered.pipe(first()).subscribe(x => {console.log('does not work', x);});

in the HelloComponent itself i'm waiting for some async tasks to be finished and afterwards emit slideContentRendered but i do not get into the subscribe method body.

Here you can see an example application https://stackblitz.com/edit/angular-krx3y6

How can i get access to the outputs? If i'm trying the same with a viewref with the following code it works:

const componentRef = viewContainerRef.createComponent(componentFactory);
componentRef.instance.slideContentRendered.pipe(first()).subscribe(x => {console.log('it works', x);});

Solution

  • Use a BehaviorSubject, it will emit value whenever there is a listener somewhere. Subscribing to EventEmitter only triggers when there is a direct listener present when emitting. So do the following changes:

    slideContentRendered = new BehaviorSubject<string>('hey');
    
    ngAfterViewInit() {
      console.log('AfterViewInitTriggered');
      this.slideContentRendered.next('teeest!')
    }
    
    trigger() {
      this.testService.renderHtmlFromPresentation().subscribe(x => console.log(x));
    }
    

    FORKED STACKBLITZ