【发布时间】:2020-11-14 23:24:31
【问题描述】:
我用编译器的compileModuleAsync 编译了一个 Angular 模块(以动态加载模块),并希望将模块的一个组件插入到视图中。
我尝试将组件插入ViewContainer,但组件不会自动检测更改。每次更新组件的属性时,我都应该调用changeDetectorRef.detectChanges。
有什么方法可以在不使用changeDetectorRef 的情况下实现这一点?
Angular 版本是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.
}
【问题讨论】:
-
如何将输入传递给组件?你在哪里调用 changeDetectorRef?
-
嗨@David,传递输入很好,我更新了问题。只想让它自动检测变化。
-
这似乎工作正常:stackblitz.com/edit/…
-
哦,我可以看到它有效。但它在我这边不起作用
-
你能用你的真实代码试试 stackblitz 吗?
标签: angular angular2-changedetection angular-dynamic-components change-detector-ref