I have a nested form group with a button ("Confirm") and I want the parent form to be invalid until the button on the child has been pushed. However it seems like the validator is designed strictly for inputs.
Is it possible to have form validation on just a button push or a property that's not in my html at all?
I've attempted with the following code but feel like I'm barking up the wrong tree.
a custom validator like this:
function isConfirmedValidator(confirmed: boolean): ValidatorFn {
return (c: AbstractControl): { [key: string]: boolean } | null => {
if (confirmed) {
return null;
} else {
return { "notConfirmed": true };
}
};
}
local prop:
isConfirmed = false;
button hooked into this:
onConfirm = () => {
this.isConfirmed = true;
}
init nested form:
this.nestedForm = this.formBuilder.group({}, isConfirmedValidator(this.isConfirmed));
Edit: Should I have a hidden field in my html that I tie to a formControl? Seems too hacky but maybe is the cleanest way?
You can add a required control to your form, and set value to it when the user click on the button:
TS:
userForm: FormGroup = this.fb.group({
name: ['My name', [Validators.required]],
button: [null, [Validators.required]],
});
HTML:
<button type="button" (click)="userForm.get('button').setValue(true)">
Click required
</button>