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?
You can use addValidators()
and removeValidators()
to dynamically add or remove validators:
this.pricingForm.controls.price.controls.weight_purchase_price.valueChanges.subscribe(
(value) => {
if (value) {
this.pricingForm.controls.weight.addValidators(
Validators.required
);
this.pricingForm.controls.weight_unit_price_measurement_type.addValidators(
Validators.required,
);
} else {
this.pricingForm.controls.weight.removeValidators(
Validators.required,
);
this.pricingForm.controls.weight_unit_price_measurement_type.removeValidators(
Validators.required,
);
}
},
);
Also make sure to unsubscribe from the subscription to prevent memory leaks.
2