after I dynamically add the form control, the rrp.invalid
does not work when the input is touched
. It works in case if I write something and remove it.
Initially, it works well, but when I remove rrp
form control and add it dynamically, it does not work as expected
component ts file
ngOnInit() {
this.form = this.fb.group({
rrp: ['', [Validators.required]],
priceType: [PricingType.Fixed, []],
});
this.form.get('priceType').valueChanges.pipe(
takeUntil(this.unsubscribe),
debounceTime(500)
).subscribe((chosenPriceType) => {
this.managePricingControls(chosenPriceType);
});
}
private managePricingControls(priceType: string) {
switch(priceType) {
case PricingType.Fixed:
this.addFixedPriceControls();
break;
case PricingType.Subscription:
this.removeFixedPriceControls();
break;
default:
break;
}
}
private addFixedPriceControls() {
this.form.addControl(
'rrp',
this.fb.control(0, Validators.required)
);
this.form.get('rrp').updateValueAndValidity()
this.form.addControl(
'expiresInMonth',
this.fb.control(0)
);
}
get rrp() {
return this.form.get('rrp');
}
template
<div *ngIf="rrp" class="form-group required">
<label for="rrp" title="Recommended Retail Price">RRP</label>
<input
type="text"
class="form-control "
id="rrp"
formControlName="rrp"
appPositiveNumber
[decimal]="true"
[decimalNumbers]="2"
autocomplete="off"
>
<span class="currency">{{currency}}</span>
<div *ngIf="rrp?.invalid && (rrp?.dirty || rrp?.touched)" class="alert alert-danger">
Recommended Retail Price is required
</div>
</div>
note: I've tried to put setTimeout(() => this.form.get('rrp').updateValueAndValidity(), 0);
as well
So, the solution is that I pass validation in the wrong way. Instead of
I should've add the control like below:
The
Validators.required
as element of array.