推荐使用import
而不是require
来加载模块。如果非要使用require
,可以使用Angular提供的NgModuleFactoryLoader
来动态加载组件。
示例代码:
使用import
加载模块:
import { Component } from '@angular/core';
import { MyService } from './my.service';
@Component({
selector: 'app-my-component',
template: `
Welcome, {{ name }}!
`,
})
export class MyComponent {
constructor(private myService: MyService) {}
name = this.myService.getName();
loadMyOtherComponent() {
import('./my-other-component/my-other-component.component').then(module => {
// Do something with the module, such as rendering the dynamic component
});
}
}
使用NgModuleFactoryLoader
动态加载组件:
import { Component, NgModuleFactoryLoader, ViewChild, ViewContainerRef } from '@angular/core';
@Component({
selector: 'app-my-component',
template: `
`,
})
export class MyComponent {
@ViewChild('target', { read: ViewContainerRef }) target: ViewContainerRef;
constructor(private loader: NgModuleFactoryLoader) {}
loadMyOtherComponent() {
this.loader.load('./my-other-component/my-other-component.module#MyOtherComponentModule').then(factory => {
const moduleRef = factory.create(this.target.injector);
const componentFactory = moduleRef.componentFactoryResolver.resolveComponentFactory(MyOtherComponent);
this.target.clear();
this.target.createComponent(componentFactory);
});
}
}