I have a formgroup called fruits created
fruits: FormGroup = formBuilder.group({
numberOfFruits: [0,Validators.min(0)],
apple: false,
mangoes: false
});
and the html is as follows:
<div formGroupName="fruits">
<div>
<p>Key in the number of fruits you want to select</p>
</div>
<div>
<input readonly matInput formControlName="numberOfFruits" type="number">
</div>
<mat-checkbox formControlName="apple">Apple</mat-checkbox>
<mat-checkbox formControlName="mangoes">Mangoes</mat-checkbox>
</div>
I would want to perform validation as follows:
I have created a validation for the group fruits
by writing individual conditions as follows:
if (group.controls['numberOfFruits'].value === 1 || (group.controls['numberOfFruits'].value == 2 &&
group.controls['apple'].value === true)) {
group.controls['mangoes'].patchValue(false);
}
if (group.controls['numberOfFruits '].value == 1 || (group.controls['numberOfFruits'].value == 2 && group.controls['mangoes'].value === true)) {
group.controls['apple'].patchValue(false);
}
Is there a better and effective way to achieve this?
I think is better subscribe to group.valueChanges (remember you need subscribe after create the formGroup). Some like
group.valuesChange.subscribe(res=>{
if (res.numberOfFuits>=1)
{
..enable apple and mangos..
if (res.numberOfFuits==1)
{
if apple, mangos=false; //<--remember {emitEvent:false}
if mangos, apple=false
}
}
else
{
disable apple and mangos and set value to false;
}
})
And you need make a custom formValidation to control when numberOfFruits>2