Skip to content

Instantly share code, notes, and snippets.

@sp90
Last active March 2, 2023 10:20
Show Gist options
  • Save sp90/9b435196fe17a893d81d2ec13f9c0a32 to your computer and use it in GitHub Desktop.
Save sp90/9b435196fe17a893d81d2ec13f9c0a32 to your computer and use it in GitHub Desktop.
Conditional Angular Reactive Form
import { ValidatorFn } from '@angular/forms';
export type BooleanFn = () => boolean;
export function conditionalValidator(
predicate: BooleanFn,
validator: ValidatorFn,
errorNamespace?: string
): ValidatorFn {
return (formControl) => {
if (!formControl.parent) {
return null;
}
let error = null;
if (predicate()) {
error = validator(formControl);
}
if (errorNamespace && error) {
const customError = {};
customError[errorNamespace] = error;
error = customError;
}
return error;
};
}
import { conditionalValidator } from './custom-validators';
export type Types = 'a' | 'b';
@Component({
selector: 'app-component',
templateUrl: './component.component.html',
styleUrls: ['./component.component.scss']
})
export class SomeComponent {
costForm = this.fb.group({
type: this.fb.control<Types>('a', [Validators.required]),
fieldA: [
null,
[conditionalValidator(this.checkType('a'), Validators.required, 'Required')]
],
fieldB: [
null,
[conditionalValidator(this.checkType('b'), Validators.required, 'Required')]
],
anotherField: [null, [Validators.required]]
});
constructor(private fb: FormBuilder) {}
private checkType<Types>(type: Types) {
return () => {
const fieldType = this.myForm.controls.type.value;
return type === fieldType;
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment