Angular 15: Using hostDirectives: [NgIf] is throwing No provider for TemplateRef found

891 views Asked by At

I am attempting to leverage NgIf as a host directive to show and hide content. There are a number of blog posts that are all doing the same pattern and there is no mention of this issue or how to work around it. I have tried a number of things including adding NgIf as an import and even a provider in the module with no luck.

My directive works fine until I start to add NgIf as a hostDirectives entry you can see here everything works fine until you uncomment lines 63,69,78. If you open the console you will see the TemplateRef error.

https://stackblitz.com/edit/ng-15-directive-composition-api-48mby7?file=src%2Fapp%2Fapp.component.ts

Examples of the pattern of leveraging NgIf in your custom directive.

https://dev.to/this-is-angular/directives-in-practice-user-role-based-element-control-49id

https://netbasal.com/making-dry-conditional-structural-directives-using-angular-directive-composition-api-bc346672445d

What am I missing here? I have dealt with this error for years and generally its a quick fix.

1

There are 1 answers

4
Mehyar Sawas On BEST ANSWER

Solution:

Do not provide the ngIf in your component. Create a structural directive that provides the ngIf in hostProviders exactly as in the examples above.

Analysis

In your code you are providing ngIfin a component and not in a directive as in the examples you have posted. The structural directive ngIf depends on TemplateRef (ng-template) and that is why you are getting an error.

It works only with structural directives because elements that use structural directives prefixed by * are converted by angular to an ng-template element which then allow the structural directives like ngIf and ngFor to change the dom layout.

Here is a working Example