0
Follow
2
View

Replace deprecated Angular ComponentFactoryResolver, ComponentFactory

dizheng1982 注册会员
2023-01-25 09:57

In Angular 13 the new API removes the need for ComponentFactoryResolver being injected into the constructor, like you did in your code.

Now to dynamically create a component you have to use ViewContainerRef.createComponent without using the factory.

So, instead of using

const compFactory: ComponentFactory = this.resolver.resolveComponentFactory(DynamicTableComponent);

you can do:

import {ViewContainerRef} from '@angular/core';

/**
your code logic
*/

constructor(private viewContainerRef: ViewContainerRef)

public addTable(): void {
   const component = this.viewContainerRef.createComponent(YourElement);

}
dlzthzzh 注册会员
2023-01-25 09:57

After spending a few hours I have reached the correct solution for Angular 13 Ivy with the new Update of Component API:

First you need to create a directive, the best would be in a subfolder called 'directives', you can do it manually or use the command:

ng generate directive directives/DynamicChildLoader

This will generate the file:

dynamic-child-loader.directive.ts

There your code will need to be something like:

import { Directive, ViewContainerRef } from '@angular/core';
    
@Directive({
  selector: '[dynamicChildLoader]',
})
export class DynamicChildLoaderDirective {
  constructor(public viewContainerRef: ViewContainerRef) {}
}

Now in your component go to the .HTML and you need to include this:


And in your .TS:

@ViewChild(DynamicChildLoaderDirective, { static: true })
dynamicChild!: DynamicChildLoaderDirective;
    
ngOnInit(): void {
  this.loadDynamicComponent();
}
    
private loadDynamicComponent() {
  this.dynamicChild.viewContainerRef.createComponent(YourDynamicChildComponent);
}

Don't forget that in your app.module.ts or the module you are using to include in the Declarations part your DynamicChildLoaderDirective

@NgModule({
  declarations: [MyExampleComponent, DynamicChildLoaderDirective],
  imports: [CommonModule, ComponentsModule],
})

About the Author

Question Info

Publish Time
2023-01-25 09:57
Update Time
2023-01-25 09:57

Related Question

登录或注册按钮在Angular/Firebase中无效

在点击图像Angular Typescript时填充表单字段

Angular条件基于条件的路由

在Angular中使用ngIf改变表格中td的背景图像

Angular生成器失败——缺少package.json

angular 13中的HTML注入

我如何在nodeJs中自动启动和重新加载index.js,当我在前端- Angular上做更改时?

Angular循环依赖:处理它的最佳实践

我应该在Angular库项目中使用哪个tsconfig路径?

Angular 14中,PrimeNg不能预选多选择