简体   繁体   中英

Angular Form Control Dynamic Parameter

So I have a form that I need to add validators to and some of the controls are required only if a certain condition is matched by another control. What is a good way to do this. I originally made a custom validator function that I passed in a parameter to the function to determine if it should be required, but it keeps the original value of the parameter not matter if I update other controls in the form.

public static required(bookType: BookType, controlKey: string) {
        return (control: AbstractControl): ValidationErrors | null => {
            if(this.isRequired(bookType,controlKey)){
                return !control.value? {required: true} : null
            }
            return null;
        }
    }

the form book type is originally DIGITAL and I change the book type to PRINT it stays DIGITAL.

This feels like it should stay a form-control validator since I am validating one value, not the group.

What would be the best way to make this work?

You need to implement a cross fields validator. So you will be able to play with values of these fields inside the validator function. Details:https://angular.io/guide/form-validation#cross-field-validation

const deliveryAddressRequiredValidator: ValidatorFn = (control: AbstractControl): ValidationErrors | null => {
    const bookType = control.get('bookType');
    const deliveryAddress = control.get('deliveryAddress');

    if (bookType && deliveryAddress && bookType.value === 'PRINT' && Validators.required(deliveryAddress)) {
        return { deliveryAddressRequired: true };
    }

    // no validation for book type DIGITAL
    return null;
};

Usage:

this.form = this.formBuilder.group({
    bookType: ['', [Validators.required]],
    deliveryAddress: [''],
}, {validators: deliveryAddressRequiredValidator});

To display error in the template use: form.errors?.deliveryAddressRequiredValidator

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM