一个人可以在第三方库的DOM元素中渲染Angular 2组件吗? [英] Can one render Angular 2 Components inside DOM elements from third party libraries?
问题描述
假设我有一个Angular 2应用程序,该应用程序包装了第三方库(例如,由Leaflet Mapping API自己执行的DOM管理).
Suppose I have an Angular 2 app that wraps a third party library such as the Leaflet Mapping API that does it's own DOM management.
我正在从Angular调用第三方库组件.
Invoking the third party library components from Angular I have working.
但是,在Leaflet示例中,如果我要渲染我的Angular组件之一/inside/第三方库渲染的标记怎么办.
However, in the Leaflet example, what if I want to render one of my Angular components /inside/ some markup rendered by the third party library.
例如,是否可以在Leaflet弹出窗口中从Angular 2应用程序渲染组件? http://leafletjs.com/reference-1.1.0.html#popup
For example, is it possible to render a component from my Angular 2 app inside a Leaflet popup? http://leafletjs.com/reference-1.1.0.html#popup
或者在一般情况下,如果我引用了Angular外部的DOM元素,是否有API可以将Angular组件附加到该DOM元素并进行管理?
Or in the general case, if I have a reference to a DOM element "outside" of Angular, is there an API available to append an Angular component to that DOM element and manage it?
推荐答案
是的,如果动态实例化组件,则可以将DOM元素传递给组件创建方法.此DOM元素将充当新创建的组件的宿主. 但是,您必须手动触发更改检测. Angular CDK 通过引入门户网站主机来解决该问题.
Yes, if you instantiate a component dynamically, you can pass the DOM element to the component creation method. This DOM element will act as host of the newly created component. However, you would have to manually trigger change detection. Angular CDK solves that problem by introducing portal hosts.
这是基本示例:
@Component({
selector: 'a-comp',
template: `<h2>I am {{name}}</h2>`
})
export class AComponent {
name = 'A component';
}
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
</div>
`,
})
export class AppComponent {
name = `Angular! v${VERSION.full}`;
componentRef;
constructor(r: ComponentFactoryResolver, i: Injector) {
const someDOMElement = document.querySelector('.host');
const f = r.resolveComponentFactory(AComponent);
this.componentRef = f.create(i, [], someDOMElement);
}
ngDoCheck() {
this.componentRef.changeDetectorRef.detectChanges();
}
}
这是朋克.
您可以在文章中阅读有关动态组件的更多信息:
You can read more about dynamic components in the article:
这篇关于一个人可以在第三方库的DOM元素中渲染Angular 2组件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!