0
votes

I've built a custom password validator for a template driven form based on this tutorial: https://juristr.com/blog/2016/11/ng2-template-driven-form-validators/#building-a-custom-validator

However, I'd like to use it on multiple forms which are in different parts in the application. I keep getting the error:

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.

If I add the validator to the higher module like it suggests, it doesn't work anymore. The validator is never reached. It seems to need to be imported in the module directly holding the form to be effective.

Any ideas?

1
Just remove PasswordValidator from both i.e. SignupModule and AuthModule instead add it in root module so that you can use it in entire application - Suryan
Or why not created a SharedModule that exports this validator to any module that imports this SharedModule? - Alexander Staroselsky
^I tried both of those, which is what I meant by "If I add the validator to the higher module like it suggests" - metalkat

1 Answers

2
votes

Issue

This is the error every Angular developer get in the beginning. The issue is lack of understanding how Module works in terms of Declaration of Component and Directives

In your case, you a Directive and you are trying to use it in two different Modules so you had declare in two different Modules. But Angular starts complaining that you had declared the same component in more than one Module.

Now what developer does, is to move the Directive to higher Module thinking that it will be available in all its children Modules but wait it won't work.

Fix

The actual issue here is the way we think about the Module import. We think if we had the Directives or Component at the higher level, it will be available in all the its children but not necessarily ( its depends on the execution sequence ).

Just think in other way around. Does my current Module import all required Modules which contains Directive and Component. That is the case where we create the ShareModule which contains all re-used Components and Directives and we just import it wherever it requires.

In short, create a SharedModule and declare your common Directives and Components in it and import this Module wherever required.

Please refer this nice official article on shared module - https://angular.io/guide/sharing-ngmodules