Angular 15: 使用 hostDirectives: [NgIf] 报错,找不到 TemplateRef 的提供程序

huangapple go评论61阅读模式
英文:

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

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

我在这里缺少什么?我已经处理了这个错误多年,通常都能迅速解决。

英文:

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

得分: 2

解决方案:

不要在你的组件中提供ngIf。创建一个结构型指令,在hostProviders中提供ngIf,就像上面的示例一样。

分析:

在你的代码中,你在组件中提供了ngIf,而不是像你发布的示例中那样在指令中提供。结构型指令 ngIf 依赖于TemplateRef (ng-template),这就是你出错的原因。

它仅适用于结构型指令,因为使用以*为前缀的结构型指令的元素会被Angular转换为一个ng-template元素,然后允许结构型指令如ngIfngFor改变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 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

huangapple
  • 本文由 发表于 2023年6月15日 02:32:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76476599.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定