I compile an Angular module (to load the module dynamically) with compiler's compileModuleAsync
and want to insert a component of the module into view.
I tried to insert the component into ViewContainer
but the component doesn't detect changes automatically. I should call changeDetectorRef.detectChanges
each time when I update a component's property.
Is there any way to achieve this without using the changeDetectorRef
?
Angular version is 10.0.4
.
Example code that I load the component:
The Component where I load another component:
<ng-template #dynamic></ng-template>
@ViewChild('dynamic', { read: ViewContainerRef })
dynamic: ViewContainerRef;
constructor(
private compiler: Compiler,
private injector: Injector
) {}
async ngAfterViewInit() {
// Load a module dynamically
const exampleModule = await import('../example/example.module').then(m => m.ExampleModule);
const moduleFactory = await this.compiler.compileModuleAsync(exampleModule);
const moduleRef = moduleFactory.create(this.injector);
const componentFactory = moduleRef.instance.resolveComponent();
const ref = container.createComponent(componentFactory, null, moduleRef.injector);
}
ExampleModule:
@NgModule({
declarations: [
ExampleComponent
],
imports: [...]
})
export class ExampleModule {
constructor(private componentFactoryResolver: ComponentFactoryResolver) { }
public resolveComponent(): ComponentFactory<ExampleComponent> {
return this.componentFactoryResolver.resolveComponentFactory(ExampleComponent);
}
}
An example case of calling detectChanges
:
ExampleComponent
<button (click)="toggle()">Show/Hide</button>
<span *ngIf="show">Show</span>
public toggle() {
this.show = !this.show;
this.cdr.detectChanges(); // <- I want to not use this.
}
I use this service to create component an set inputs:
Usage: