gpt4 book ai didi

javascript - 如何在 Angular 中使用第三方库动态创建组件?

转载 作者:行者123 更新时间:2023-12-05 00:27:04 25 4
gpt4 key购买 nike

使用 Angular 10
SO上有很多与此类似的问题,但我还没有找到一个可以回答我的情况的问题。
我希望有人可以指导我。
我正在使用第三方库来显示 360° 照片。这个第三方库有一个内置的 API 来显示场景中的热点。只需为库提供您想要成为热点的元素,剩下的就交给它了。
我的大部分工作都按预期工作,但有几件没有。
到目前为止,我正在动态生成我的组件,如下所示:

this._hotspotFactory = this.resolver.resolveComponentFactory(HotspotComponent);
const component = this._hotspotFactory.create(this.injector);

//Hydrate component with bunch of data
component.instance.id = data.id;
...

// Create the Hotspot with Third Party
// Calling this third party method injects the native element into the DOM.
// Passing the nativeElement in. Looks great at first glance.
const hotspot = this._scene.createHotspot(data, component.location.nativeElement);

this.appRef.attachView(component.hostView);
component.hostView.detectChanges();

if(component.instance.over.observers.length) {
hotspot.on('over', (evt) => {
this.zone.run(() => {
component.instance.over.emit(evt);
});
});
}

if(component.instance.out.observers.length) {
hotspot.on('out', (evt) => {
this.zone.run(() => {
component.instance.out.emit(evt);
});
});
}

if(component.instance.navigate.observers.length) {
hotspot.on('click', (evt) => {
this.zone.run(() => {
component.instance.navigate.emit(evt);
})
});
}

没有抛出任何错误,我成功地看到了热点应该在场景中的位置。 HotspotComponent 中的偶数数据插值模板按预期发生。
但是, [ngStyle]绑定(bind)永远不会导致 HotspotComponent 中的动态样式.
我 99% 确定这是因为组件中没有进行更改检测。
我正在使用 this.appRef.attachView(component.hostView) 手动附加 View 因为第三方负责将元素注入(inject) DOM,而不是 Angular。因此 Angular 需要了解它,以便执行变更检测。
即使手动调用 attachView ,我仍然认为 Angular 不知道 View 中的这个组件,因为 Angular Chrome 扩展调试器没有在其开发工具中将其注册为 View 中的已知组件....尽管在屏幕上和在DOM。
我错过了什么?

最佳答案

组件有什么变化检测策略?
当一个组件被添加到一个 View 中时,它的生命周期钩子(Hook)将被 angular( ngOninit , ngAfterContentInit 等) 触发。在这些中记录一些内容,看看是否正在调用主题生命周期钩子(Hook)。无论更改检测策略如何,在组件添加到 View 后,都应在组件上进行一个更改检测周期。
如果生命周期钩子(Hook)调用没有发生,那么这意味着 Angular 不涉及将元素添加到 DOM。

关于javascript - 如何在 Angular 中使用第三方库动态创建组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70389032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com