Angular 2 conditional Validators.required?

前端 未结 5 1236
孤街浪徒
孤街浪徒 2020-12-09 01:33

How should I go about conditionally requiring a form field? I made a custom validator, but the conditional variables that I pass to the custom validator are static and remai

5条回答
  •  没有蜡笔的小新
    2020-12-09 02:05

    I created a validator that accepts a function callback which allows me to make the validator reusable, but I can't seem to find a good way to make sure I call updateValueAndValidity() on the control with this validator without having to manually call it when the other control's value changes.

    Validator

    export class ValidationService {
        static conditionalRequired = (isRequiredFunction: Function) => {
            return (control: Control) => {
               if (!control.value && isRequiredFunction())
               ...
    

    Component Page

    private myControl1: Control = 
        new Control("", ValidationService.conditionalRequired(() => 
            { return this && this.model && this.model.SomeProperty === 'SomeValue' } ));
    
    private myControl2: Control = 
        new Control("", 
        ValidationService.conditionalRequired(this.isControl2Required.bind(this)));
    
    isControl2Required() { 
        return someCondition;
    }
    

提交回复
热议问题