Last active
March 2, 2023 10:20
-
-
Save sp90/9b435196fe17a893d81d2ec13f9c0a32 to your computer and use it in GitHub Desktop.
Conditional Angular Reactive Form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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