如何在模块之间共享自定义验证器
How to share custom validators between modules
我根据本教程为模板驱动的表单构建了自定义密码验证器:https://juristr.com/blog/2016/11/ng2-template-driven-form-validators/#building-a-custom-validator
但是,我想在应用程序不同部分的多个表单上使用它。我不断收到错误消息:
Type PasswordValidator is part of the declarations of 2 modules:
SignupModule and AuthModule! Please consider moving PasswordValidator to a higher module that imports SignupModule and AuthModule.
如果我像它建议的那样将验证器添加到更高的模块,它就不再起作用了。永远不会到达验证器。好像需要在直接拿着表格的模块中导入才有效。
有什么想法吗?
Issue
这是每个 Angular
开发人员一开始都会遇到的错误。问题是缺乏对模块在 Declaration
of Component
和 Directives
方面的工作方式的理解
在你的例子中,你是一个 Directive
并且你试图在两个不同的模块中使用它,所以你在两个不同的 Modules
中声明了。但是 Angular
开始抱怨您在多个 Module
.
中声明了相同的组件
现在开发人员所做的是将 Directive
移动到更高 Module
并认为它将在其所有子项中可用 Modules
但等待它不会起作用。
Fix
这里的实际问题是我们考虑模块导入的方式。我们认为如果我们在更高级别有 Directives
或 Component
,它将在其所有子级中可用,但不一定(它取决于执行顺序)。
换个角度想吧。我当前的 Module
是否导入所有必需的 Modules
,其中包含 Directive
和 Component
。在这种情况下,我们创建了 ShareModule
,其中包含所有重复使用的 Components
和 Directives
,我们只需在需要的地方导入它。
In short, create a SharedModule
and declare your common Directives
and Components
in it and import this Module
wherever required.
请参考这篇关于共享模块的不错的官方文章 - https://angular.io/guide/sharing-ngmodules
我根据本教程为模板驱动的表单构建了自定义密码验证器:https://juristr.com/blog/2016/11/ng2-template-driven-form-validators/#building-a-custom-validator
但是,我想在应用程序不同部分的多个表单上使用它。我不断收到错误消息:
Type PasswordValidator is part of the declarations of 2 modules:
SignupModule and AuthModule! Please consider moving PasswordValidator to a higher module that imports SignupModule and AuthModule.
如果我像它建议的那样将验证器添加到更高的模块,它就不再起作用了。永远不会到达验证器。好像需要在直接拿着表格的模块中导入才有效。
有什么想法吗?
Issue
这是每个 Angular
开发人员一开始都会遇到的错误。问题是缺乏对模块在 Declaration
of Component
和 Directives
在你的例子中,你是一个 Directive
并且你试图在两个不同的模块中使用它,所以你在两个不同的 Modules
中声明了。但是 Angular
开始抱怨您在多个 Module
.
现在开发人员所做的是将 Directive
移动到更高 Module
并认为它将在其所有子项中可用 Modules
但等待它不会起作用。
Fix
这里的实际问题是我们考虑模块导入的方式。我们认为如果我们在更高级别有 Directives
或 Component
,它将在其所有子级中可用,但不一定(它取决于执行顺序)。
换个角度想吧。我当前的 Module
是否导入所有必需的 Modules
,其中包含 Directive
和 Component
。在这种情况下,我们创建了 ShareModule
,其中包含所有重复使用的 Components
和 Directives
,我们只需在需要的地方导入它。
In short, create a
SharedModule
and declare your commonDirectives
andComponents
in it and import thisModule
wherever required.
请参考这篇关于共享模块的不错的官方文章 - https://angular.io/guide/sharing-ngmodules