簡體   English   中英

Angular Form Control 動態參數

[英]Angular Form Control Dynamic Parameter

所以我有一個表單,我需要向其中添加驗證器,並且只有在某個條件與另一個控件匹配時才需要一些控件。 有什么好的方法可以做到這一點。 我最初制作了一個自定義驗證器函數,我將一個參數傳遞給該函數以確定是否需要它,但是如果我更新表單中的其他控件,它會保留參數的原始值。

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;
        }
    }

表單書籍類型最初是 DIGITAL,我將書籍類型更改為 PRINT,它保持 DIGITAL。

這感覺它應該保持表單控件驗證器,因為我正在驗證一個值,而不是組。

使這項工作發揮作用的最佳方法是什么?

您需要實現一個跨字段驗證器。 因此,您將能夠在驗證器函數中使用這些字段的值。 詳情: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;
};

用法:

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

要在模板中顯示錯誤,請使用: form.errors?.deliveryAddressRequiredValidator

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM