Reputation: 1207
Angular reactive form below. There are 2 buttons, one submit & one fetch detail.
Working Submit button have form validation, only mobile number is mandatory. This had achieved using required in component.
How can I do this
Another button Fetch, I need to validate 2 fields Id & date is mandatory, and show the error message in <span>
, This is not working
Form
<form role="form" [formGroup]="pForm" >
<div class="row display-flex">
<div class="col-lg-3 col-md-4 col-sm-6">
<label>Id </label>
<input class="form-control form-control-sm" formControlName="id" type="number" />
<span *ngIf="submitted && f.errors && f.errors.idRequired"
class="tooltiptext">{{'Id is required'}}</span>
</div>
<div class="col-lg-3 col-md-4 col-sm-6">
<label> Date </label>
<p-calendar type="number" dateFormat="dd-mm-yy" formControlName="eDate"
monthNavigator="true" appendTo="body" yearNavigator="true"
yearRange="1930:2030" >
</p-calendar>
<span *ngIf="submitted && f.errors && f.errors.eDateRequired"
class="tooltiptext">{{'Id is required'}}</span>
</div>
<div class="col-lg-3 col-md-4 col-sm-6">
<button class="btn btn-sm btn-primary bw" (click)="fetch()"
translate>traveler.getDetails</button>
</div>
<div class="col-lg-2 col-md-2 col-sm-3">
<label>Mobile <span class="mdtr">*</span></label>
<input type="text" numeric class="form-control form-control-sm" [readonly] = "gsm" formControlName="mobileNo" />
<span *ngIf="submitted && f.mobileNo.errors" class="tooltiptext" >{{'Mobile is required'}}</span>
</div>
</div>
<button class="btn btn-sm btn-primary" type="submit" (click)="saveForm()">
Save
</button>
</form>
Here form intialized, getDetail() I tried set other 2 fields as mandatory , but didnt worked
this.pForm = this.fb.group({
id: [null],
eDate: [null],
mobileNo: ["", Validators.required]
})
get f() {
return this.pForm.controls;
}
getDetail() {
this.submitted = true;
this.pForm.setValidators({
idRequired: true,
eDateRequired: true
});
}
saveForm() {
this.submitted = true;
if (this.pForm.invalid) {
Swal.fire("mandatory fiels are missing);
return;
}
}
Upvotes: 0
Views: 2121
Reputation: 3520
When you click on getDetails, you have to explicitly set the validators for the other fields as below.
Moreover, you have to update the validity of the existing form as below.
getDetail() {
this.submitted = true;
this.pForm.get('id').setValidators([
Validators.required,
]);
this.pForm.get('eDate').setValidators([
Validators.required,
]);
this.pForm.controls['id'].updateValueAndValidity()
this.pForm.controls['eDate'].updateValueAndValidity()
}
On submit, you can remove the validators, as below
this.pForm.controls['id'].setValidators([]);
this.pForm.controls['eDate'].setValidators([]);
this.pForm.controls['id'].updateValueAndValidity()
this.pForm.controls['eDate'].updateValueAndValidity()
Here is the working Stackblitz
Upvotes: 1