Can one render Angular 2 Components inside DOM ele

2019-01-24 21:30发布

问题:

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.

Invoking the third party library components from Angular I have working.

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.

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

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?

回答1:

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.

Here is the basic example:

@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();
    }
}

Here is the plunker.

You can read more about dynamic components in the article:

  • Here is what you need to know about dynamic components in Angular