Ranjan
Ranjan

Reputation: 475

Anguler2 - Unhandled Promise rejection: No provider for ViewContainerRef! ( In dynamic template )

I am trying to implement dynamic component. My requirement is, I have three class- LayoutComponent, MenuService and DynamicService. LayoutComponent is used to call the MenuService's method to perform some basic operation, after performing operation, MenuService's method again call to DynamicService's method for creating dynamic component.

Here is my Plunker with the following error which it gives

Unhandled Promise rejection: No provider for ViewContainerRef! ;

Upvotes: 23

Views: 21557

Answers (2)

Masoud Darvishian
Masoud Darvishian

Reputation: 3964

In my case, I was using ng2-toastr and it caused the problem.

Calling setRootViewContainerRef() of toastr will solve your problem.

constructor(dialogService: DialogService,
        private toastr: ToastsManager,
        private vcr: ViewContainerRef) {
        super(dialogService);
        this.toastr.setRootViewContainerRef(vcr);
    }

Upvotes: 1

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657721

ViewContainerRef can only be injected to components or directives, but not to services.

Components and directives get the ViewContainerRef of the element where they itself are attached. A service isn't attached to any view.

What you can do is to inject ViewContainerRef and a service to a component and then in the constructor pass the ViewContainerRef to the service. Every service or component that injects this service can access the ViewContainerRef it holds.

Upvotes: 57

Related Questions