cal*_*r47 9 javascript angular angular-changedetection
使用角度 10
\nSO 上有很多与此类似的问题,但我还没有找到一个可以回答我的情况的问题。
\n我希望有人能指导我。
\n我正在使用第三方库来显示 360\xc2\xb0 照片。这个第三方库有一个内置的API来显示场景中的热点。只需向库提供您想要成为热点的元素,它就会处理其余的事情。
\n我的大部分内容都按预期工作,但有一些部分没有按预期工作。
\n到目前为止,我正在动态生成我的组件,如下所示:
\nthis._hotspotFactory = this.resolver.resolveComponentFactory(HotspotComponent);\nconst component = this._hotspotFactory.create(this.injector);\n\n//Hydrate component with bunch of data\ncomponent.instance.id = data.id;\n...\n\n// Create the Hotspot with Third Party\n// Calling this third party method injects the native element into the DOM. \n// Passing the nativeElement in. Looks great at first glance. \nconst hotspot = this._scene.createHotspot(data, component.location.nativeElement);\n\nthis.appRef.attachView(component.hostView);\ncomponent.hostView.detectChanges();\n\nif(component.instance.over.observers.length) {\n hotspot.on(\'over\', (evt) => {\n this.zone.run(() => {\n component.instance.over.emit(evt);\n });\n });\n}\n\nif(component.instance.out.observers.length) {\n hotspot.on(\'out\', (evt) => {\n this.zone.run(() => {\n component.instance.out.emit(evt);\n });\n });\n}\n\nif(component.instance.navigate.observers.length) {\n hotspot.on(\'click\', (evt) => {\n this.zone.run(() => {\n component.instance.navigate.emit(evt);\n })\n });\n}\n\nRun Code Online (Sandbox Code Playgroud)\n没有抛出任何错误,我成功地看到了场景中应该出现的热点。甚至模板中的数据插值HotspotComponent也会按预期发生。
但是,[ngStyle]绑定永远不会导致HotspotComponent.
我 99% 确定这是因为组件中没有进行更改检测。
\n我手动附加视图是this.appRef.attachView(component.hostView)因为第三方负责将元素注入到 DOM 中,而不是 Angular。因此 Angular 需要了解它,以便执行更改检测。
即使手动调用attachView,我仍然认为 Angular 不知道视图中的这个组件,因为 Angular Chrome 扩展调试器不会在其开发工具中将其注册为视图中的已知组件....尽管看到它在屏幕上和 DOM 中。
我缺少什么?
\n该组件有什么变化检测策略?当一个组件被添加到视图中时,它的生命周期钩子将由 Angular(ngOninit等ngAfterContentInit) 触发。在其中记录一些内容并查看是否正在调用主题生命周期挂钩。无论更改检测策略如何,在将组件添加到视图后,都应该在组件上发生一个更改检测周期。
如果生命周期钩子调用没有发生,那么这意味着 Angular 不参与将元素添加到 DOM。