简体   繁体   English

使用选择器在Angular 2中动态加载组件

[英]Load component dynamically in Angular 2 using selector

Can we load component dynamically in Angular 2 using it's selector ? 我们可以使用它的选择器在Angular 2中动态加载组件吗?

Lets say we have a component like below, 假设我们有一个类似下面的组件,

 @Component({
    moduleId: module.id,
    selector: 'my-component',
    templateUrl: 'my-component.html',
    styleUrls: ['my-component.css']   
 })
 export class MyComponent{
 }

Can we load this dynamically into a container using it's selector my-component 我们可以使用选择器my-component将其动态加载到容器中吗

<div #container ></div>

LoadComponent(selector: string){
    // Load using selector?
}

There may be a need of exporting components in the NgModule and importing the NgModule where we want to load it. 可能需要在NgModule中导出组件,并将NgModule导入我们要加载的位置。

Not sure on how to achieve this, any pointers in right direction would be very helpful. 不确定如何实现此目标,任何正确方向的指针都将非常有帮助。

Thanks in advance!! 提前致谢!!

suppose your index.html has . 假设您的index.html具有。 then in your .ts or js file, when condition ready, do this: var div = document.getElementById('container'); 然后在条件准备就绪的情况下,在您的.ts或js文件中执行以下操作:var div = document.getElementById('container');

    div.innerHTML = "<my-component></my-component>"

Well I was able to resolve this using below, 我可以使用以下方法解决此问题,

constructor(private _compiler: Compiler) {}

loadComponent = (selector: string, module: any): void => {  
  this._compiler.compileModuleAndAllComponentsAsync(module).then(_module => {
    let _componentFactories = _module.componentFactories.filter(_c => {
      // here I am using the selector
      return _c.selector === selector;
    });

    // check if component is available in the module
    if (!!_componentFactories && _componentFactories.length > 0) {
       self.testComponentContainer.clear();
       self.testComponentContainer.createComponent(_componentFactories[0]).instance;                    
    }
  });
}

Hope it helps someone.. !!! 希望它可以帮助某人.. !!!

You can load any component dynamically using ComponentResolver. 您可以使用ComponentResolver动态加载任何组件。
Add following html node into parent template 将以下html节点添加到父模板中

<div #node></div>

And your component will look like 您的组件看起来像

import { Component, ViewContainerRef, ViewChild, ComponentFactory, ComponentResolver } from '@angular/core';
import { MyComponent} from 'components/my.component';

@Component({
selector: 'app-home',
template: `<h2>Home</h2>
    <div #node></div>
 `
})

export class HomeComponent implements OnInit {
@ViewChild("node", { read: ViewContainerRef }) nodeView;
instance: MyComponent
constructor(private componentResolver: ComponentResolver) {
}

ngOnInit(): void {
    this.componentResolver.resolveComponent(MyComponent)
        .then((factory: ComponentFactory<MyComponent>) => {
             this.instance = this.nodeView.createComponent(factory);
        });
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM