Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can one render Angular 2 Components inside DOM elements from third party libraries?

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?

like image 842
Yermo Lamers Avatar asked Sep 30 '26 06:09

Yermo Lamers


1 Answers

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
like image 129
Max Koretskyi Avatar answered Oct 01 '26 18:10

Max Koretskyi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!