1

Is there a way in Angular2 to pass an object to custom validator using @input or any other technique? I have to pass an existing object to the custom validator from the parent class where the validator is included? How to achieve it

Janier
  • 3,982
  • 9
  • 43
  • 96
  • What exactly are you trying to achieve? Send the ngModel from parent to child and use the Validator on the child? Have a look at this thread https://stackoverflow.com/questions/41350584/angular2-pass-ngmodel-to-a-child-component – Hugo Noro Dec 08 '17 at 20:29

1 Answers1

0

You can create an async validator in a child, but you'd need a validator that can take an arbitrary value and not an AbstractControl. You can pass this value from a parent and then give it to such a validator as an argument.

Take a look at this code sample: https://github.com/Farata/angulartypescript/tree/master/chapter7/form-samples/src/app/async-validator

In the app component in ngOnInit(), I just pass a text to a validator function checkWorkAuthorizationV2(ssnValue). I could have passed any object if needed.

Yakov Fain
  • 11,972
  • 5
  • 33
  • 38
  • This is close to what i want.. I have the object in the component .how will i bind it to a form control? – Janier Dec 08 '17 at 20:52
  • Your @Input should be a setter. If object properties represent all form controls use setValue(). To bind a selected property to a form control use patchValue(). – Yakov Fain Dec 09 '17 at 06:29