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

后端 未结 1 511
旧巷少年郎
旧巷少年郎 2020-12-17 05:22

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

相关标签:
1条回答
  • 2020-12-17 06:03

    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
    0 讨论(0)
提交回复
热议问题