Вы можете написать пользовательскую функцию валидатора, которая применяет другую валидацию в зависимости от текущего типа пользователя:
requiredForTypes(...types: string[]): ValidatorFn {
return (control: AbstractControl) => {
if (types.indexOf(this.type) > -1) {
return Validators.required(control);
}
return null;
}
}
Затем обновите элементы управления формой, чтобы использовать настраиваемый валидатор:
this.userformGroup = this.formBuilder.group({
type: [this.type, Validators.required],
userName: new FormControl('', this.requiredForTypes('user', 'admin')),
firstName: new FormControl('', this.requiredForTypes('user', 'admin')),
lastName: new FormControl('', Validators.required),
email: new FormControl('', this.requiredForTypes('user', 'admin')),
contactNumber: new FormControl('', this.requiredForTypes('user')),
licenseNo: new FormControl('', Validators.required),
age: new FormControl('', Validators.pattern('/^-?(0|[1-9]\d*)?$/')),
birthDate: new FormControl('', this.requiredForTypes('user')),
city: new FormControl('', Validators.required),
country: new FormControl('', this.requiredForTypes('user')),
zipCode: new FormControl('', Validators.pattern('/^-?(0|[1-9]\d*)?$/')),
countryCode: new FormControl('', Validators.minLength(3)),
});
Наконец, запускайте проверку при каждом изменении типа пользователя:
this.userformGroup.controls.type.valueChanges.subscribe(type => {
this.type = type;
Object.keys(this.userformGroup.controls).forEach(key => {
if (key !== 'type') {
this.userformGroup.controls[key].updateValueAndValidity();
}
})
});
Пример StackBlitz.