我用编译器编译了一个 Angular 模块(动态加载模块),compileModuleAsync
并希望将模块的一个组件插入到视图中。
我试图将组件插入其中,ViewContainer
但组件不会自动检测到更改。changeDetectorRef.detectChanges
每次更新组件的属性时都应该调用。
有没有办法在不使用的情况下实现这一点changeDetectorRef
?
角版本是10.0.4
.
我加载组件的示例代码:
我加载另一个组件的组件:
<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);
}
示例模块:
@NgModule({
declarations: [
ExampleComponent
],
imports: [...]
})
export class ExampleModule {
constructor(private componentFactoryResolver: ComponentFactoryResolver) { }
public resolveComponent(): ComponentFactory<ExampleComponent> {
return this.componentFactoryResolver.resolveComponentFactory(ExampleComponent);
}
}
调用示例detectChanges
:
示例组件
<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.
}