没有视图的动态组件输出
Outputs on dynamic components without view
在一个 Angular 8 项目中,我使用以下代码创建了一些没有 viewref 的动态组件:
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);});
在 HelloComponent 本身中,我正在等待一些异步任务完成,然后发出 slideContentRendered 但我没有进入订阅方法主体。
在这里您可以看到一个示例应用程序
https://stackblitz.com/edit/angular-krx3y6
我怎样才能访问输出?
如果我使用以下代码对 viewref 进行相同的尝试,它会起作用:
const componentRef = viewContainerRef.createComponent(componentFactory);
componentRef.instance.slideContentRendered.pipe(first()).subscribe(x => {console.log('it works', x);});
使用 BehaviorSubject,只要某处有侦听器,它就会发出值。订阅 EventEmitter 仅在发射时存在直接侦听器时触发。因此进行以下更改:
slideContentRendered = new BehaviorSubject<string>('hey');
ngAfterViewInit() {
console.log('AfterViewInitTriggered');
this.slideContentRendered.next('teeest!')
}
trigger() {
this.testService.renderHtmlFromPresentation().subscribe(x => console.log(x));
}
在一个 Angular 8 项目中,我使用以下代码创建了一些没有 viewref 的动态组件:
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);});
在 HelloComponent 本身中,我正在等待一些异步任务完成,然后发出 slideContentRendered 但我没有进入订阅方法主体。
在这里您可以看到一个示例应用程序 https://stackblitz.com/edit/angular-krx3y6
我怎样才能访问输出? 如果我使用以下代码对 viewref 进行相同的尝试,它会起作用:
const componentRef = viewContainerRef.createComponent(componentFactory);
componentRef.instance.slideContentRendered.pipe(first()).subscribe(x => {console.log('it works', x);});
使用 BehaviorSubject,只要某处有侦听器,它就会发出值。订阅 EventEmitter 仅在发射时存在直接侦听器时触发。因此进行以下更改:
slideContentRendered = new BehaviorSubject<string>('hey');
ngAfterViewInit() {
console.log('AfterViewInitTriggered');
this.slideContentRendered.next('teeest!')
}
trigger() {
this.testService.renderHtmlFromPresentation().subscribe(x => console.log(x));
}