I recently updated the angular version and packages of my old project to the latest version and I am currently working on updating deprecated uses. Below is the version details when running ng --version and I am using Webstorm 2021.3.3.
Package Version
---------------------------------------------------------
@angular-devkit/architect 0.1303.0
@angular-devkit/build-angular 13.3.0
@angular-devkit/core 13.3.0
@angular-devkit/schematics 13.3.0
@schematics/angular 13.3.0
rxjs 7.4.0
typescript 4.6.2
In the new Angular version, the use of component factory is deprecated. The API suggests using viewContainerRef.createComponent but it gives me an error saying it is deprecated. The following code shows a sample of what I am working on.
import { Component, OnInit } from '@angular/core';
import { ViewContainerRef, Injector} from "@angular/core";
import { HelloWorldComponent } from "../../what-is-angular/hello-world/hello-world.component";
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {
constructor(private viewContainerRef: ViewContainerRef, private injector: Injector) { }
ngOnInit(): void {
}
makeDynamicComponent() {
// const resultsComponent = this.componentFactoryResolver.resolveComponentFactory(HelloWorldComponent); // deprecated
// const resultsComponentRef = resultsComponent.create(this.injector); // deprecated
const resultComponentRef = this.viewContainerRef.createComponent(HelloWorldComponent, undefined, this.injector);
}
}
What the error shows regarding the use of createComponent() and the parameter HelloWorldComponent:
Deprecated symbol used, consult docs for better alternative
deprecated ViewContainerRef.createComponent<unknown>( componentFactory: ComponentFactory<unknown>, index?: number | undefined, injector?: Injector | undefined, projectableNodes?: any[][] | undefined, ngModuleRef?: NgModuleRef<...> | undefined): ComponentRef<...>
and
TS2345: Argument of type 'typeof HelloWorldComponent' is not assignable to parameter of type 'ComponentFactory<unknown>'. Type 'typeof HelloWorldComponent' is missing the following properties from type 'ComponentFactory<unknown>': selector, componentType, ngContentSelectors, inputs, and 2 more.
Am I not using the method correctly?
CodePudding user response:
The deprecated way requires all the parameters as single value. The new way requires just the first parameter as the single value, then the rest as an object.
All you need to do in the new way is this:
this._viewContainerRef.createComponent(MyComponentComponent, {injector: this._injector});