0

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.

R. Richards
  • 24,603
  • 10
  • 64
  • 64
  • Is there a reason why you are not using Angular dependency injection for your service? – MikeOne Apr 05 '22 at 15:25
  • Here one is the Component class and other is Utility class (service). I am calling Utility class method from Component class method by instantiating through the constructor. I am using dependency injection let customUtilHandler = new CustomUtilHandler(this.viewContainerRef); – Murali krishna Konduru Apr 05 '22 at 15:33
  • That’s not DI . I’d expect private utilHandler: CustomUtilHandler in the constructor. – MikeOne Apr 05 '22 at 15:35
  • ha ha :) got it. Because I have to instantiate service class by calling the service class constructor by passing the required parameters. – Murali krishna Konduru Apr 05 '22 at 15:38
  • 1
    My issue got resolved with below solution, thank you very much @MikeOne https://stackoverflow.com/a/55471492/4128499 – Murali krishna Konduru Apr 05 '22 at 16:28

0 Answers0