'Create ViewContainerRef object in angular Utility class

In one of my scenario I have moved duplicate Angular component code to one Utility class and I am re-using the logic by calling the method in all the components.

In that Utility file logic I am using ViewContainerRef and I am executing javscript code at runtime.

Like below I have multiple components and re-using logic from Utility class in all the components. Here I am getting below error. After some research I came know that ViewContainerRef can be used only in Component or as a Directive.

Could some one please help how do I instantiate ViewContainerRef object in Utility class.

Error Message.

Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[NgIf -> ViewContainerRef]:
StaticInjectorError(Platform: core)[NgIf -> ViewContainerRef]:
NullInjectorError: No provider for ViewContainerRef!

Component class

import {ViewContainerRef} from '@angular/core';
@Component({
  selector: 'dz-page-1',
  templateUrl: './component-page-1.component.html',
  styleUrls: ['./component-page-1.component.scss']
})

export class ContentInspectPageComponent{
constructor(protected viewContainerRef: ViewContainerRef,){
handleMenuAction(event){
let customUtilHandler = new CustomUtilHandler(this.viewContainerRef);
return customUtilHandler.handleCustomForm();
}
}
}

Utility Class

@Injectable({
    providedIn: 'root'
})
export class CustomUtilHandler {
constructor( protected viewContainerRef: ViewContainerRef){
}
handleCustomForm(){
this.viewContainerRef.clear();
const component = this.viewContainerRef.createComponent("customComponent");
component.instance["data"] = inputData;
}
}

Thank you in Advance.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source