英文:
Angular 15: Using hostDirectives: [NgIf] is throwing No provider for TemplateRef found
问题
我正在尝试使用NgIf
作为宿主指令来显示和隐藏内容。有许多博客文章都在执行相同的模式,但没有提到这个问题或如何解决它。我尝试了许多方法,包括将NgIf添加为模块中的导入项甚至提供者,但都没有成功。
我的指令在不添加NgIf
作为hostDirectives
项的情况下工作正常,您可以在这里看到一切正常,直到取消注释第63、69和78行
。如果您打开控制台,将会看到TemplateRef错误
。
https://stackblitz.com/edit/ng-15-directive-composition-api-48mby7?file=src%2Fapp%2Fapp.component.ts
以下是在自定义指令中利用NgIf模式的示例。
https://dev.to/this-is-angular/directives-in-practice-user-role-based-element-control-49id
我在这里缺少什么?我已经处理了这个错误多年,通常都能迅速解决。
英文:
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
What am I missing here? I have dealt with this error for years and generally its a quick fix.
答案1
得分: 2
解决方案:
不要在你的组件中提供ngIf
。创建一个结构型指令,在hostProviders
中提供ngIf
,就像上面的示例一样。
分析:
在你的代码中,你在组件中提供了ngIf
,而不是像你发布的示例中那样在指令中提供。结构型指令 ngIf
依赖于TemplateRef (ng-template)
,这就是你出错的原因。
它仅适用于结构型指令,因为使用以*
为前缀的结构型指令的元素会被Angular转换为一个ng-template
元素,然后允许结构型指令如ngIf
和ngFor
改变DOM布局。
这里有一个可工作的示例。
英文:
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 ngIf
in 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论