angulartypescriptformsangular-reactive-forms

set angular required field if conditionally handle


here is my form:

initializePricingForm(): void {
    this.pricingForm = new FormGroup({
      price: new FormGroup({
        selling_type: new FormControl('', Validators.compose([
          Validators.required
        ])),
        unit: new FormControl('pence'),
        unit_price: new FormControl(''),
        purchase_price: new FormControl(''),
        pack_purchase_price: new FormControl(''),
        weight_purchase_price: new FormControl(''),
        weight: new FormControl(''),
        weight_unit_price_measurement_type: new FormControl(''),
      }),

      currency: new FormControl('GBP'),
    });

    this.validationMessege();
    this.subs.sink = this.pricingForm.valueChanges.subscribe(() => {
      this.emitFormData();
    });

  }

if weight_purchase_price has value set weight & weight_unit_price_measurement_type must be required, only if weight_purchase_price has value. how to implement this?


Solution

  • // Custom validator function
    function weightValidator(formGroup: FormGroup) {
      const weightPurchasePrice = formGroup.get('weight_purchase_price');
      const weight = formGroup.get('weight');
      const weightUnit = formGroup.get('weight_unit_price_measurement_type');
    
      if (weightPurchasePrice?.value) {
        if (!weight?.value || !weightUnit?.value) {
          return { required: true };
        }
      }
    
      return null;
    }
    
    initializePricingForm(): void {
      this.pricingForm = new FormGroup({
        price: new FormGroup({
          selling_type: new FormControl('', Validators.required),
          unit: new FormControl('pence'),
          unit_price: new FormControl(''),
          purchase_price: new FormControl(''),
          pack_purchase_price: new FormControl(''),
          weight_purchase_price: new FormControl(''),
          weight: new FormControl(''),
          weight_unit_price_measurement_type: new FormControl(''),
        }, { validators: weightValidator }), // Apply the custom validator to the price group
        currency: new FormControl('GBP'),
      });
    
      this.validationMessege();
      this.subs.sink = this.pricingForm.valueChanges.subscribe(() => {
        this.emitFormData();
      });
    }

    Try this