I have a form group containing 4 field
public AssetValidator: ValidatorFn[] = [Validators.min(0), Validators.max(3)]; public AssetTest: this._fb.group({ SteamTestPass: [{ value: '', disabled: this.isReadOnly }, this.AssetValidator], SteamTestFail: [{ value: '', disabled: this.isReadOnly }, this.AssetValidator], FireTestPass: [{ value: '', disabled: this.isReadOnly }, this.AssetValidator], FireTestFail: [{ value: '', disabled: this.isReadOnly }, this.AssetValidator] });
By Default there are two validators and on some condition I have to add one validator which is Validators.required for that i have to individual go to every field and set the validator
Validators.required
public resetValidator(required: boolean): void { if (required) { this.AssetValidator.push(Validators.required); // is there any short hand property for this below repetation this.AssetTest.get('SteamTestPass').setValidators(this.AssetValidator); this.AssetTest.get('SteamTestPass').updateValueAndValidity(); this.AssetTest.get('SteamTestFail').setValidators(this.AssetValidator); this.AssetTest.get('SteamTestFail').updateValueAndValidity(); this.AssetTest.get('FireTestPass').setValidators(this.AssetValidator); this.AssetTest.get('FireTestPass').updateValueAndValidity(); this.AssetTest.get('FireTestFail').setValidators(this.AssetValidator); this.AssetTest.get('FireTestFail').updateValueAndValidity(); } else { this.AssetValidator = [Validators.min(0), Validators.max(3)]; this.AssetTest.get('SteamTestPass').setValidators(this.AssetValidator); this.AssetTest.get('SteamTestPass').updateValueAndValidity(); this.AssetTest.get('SteamTestFail').setValidators(this.AssetValidator); this.AssetTest.get('SteamTestFail').updateValueAndValidity(); this.AssetTest.get('FireTestPass').setValidators(this.AssetValidator); this.AssetTest.get('FireTestPass').updateValueAndValidity(); this.AssetTest.get('FireTestFail').setValidators(this.AssetValidator); this.AssetTest.get('FireTestFail').updateValueAndValidity(); } }
You could create a customValidator that gets put on the formGroup and then using similar logic to what jotatoledon suggested checks the validity instead of setting controlValidators Link: https://angular.io/guide/form-validation#defining-custom-validators
Extract the 2 steps per field into a method? then you could do something like:
``` Array.from(Object.values(this. AssetTest.controls)).forEach(control => setAndTriggerValidators(control)) ```
There is nothing like that, sorry.
I want to avoid the setValidator repetition also Anything from the main form group can be set for all fields inside it. Something like that?
Collecting keys of form in an array and using foreach loop might help you to avoid repeation. like this:
foreach
['SteamTestPass', 'FireTestPass', 'SteamTestFail', 'FileTestFail'].forEach((field: string) => { this.AssetTest.get(field).setValidators(this.hydroTestValidator); this.AssetTest.get(field).updateValueAndValidity(); });