Currently, I am working on an Angular 15 app that utilizes a hand-coded JSON file along with the JSON server for performing CRUD operations on a "employees" JSON data.
One of the tasks at hand involves adding custom validation to a <select>
element.
Within the employee-form.component.html
file:
<form class="modal-content" #employeeForm="ngForm" (ngSubmit)="addEmployee(employeeForm)">
<!-- Modal Header -->
<div class="modal-header py-2">
<h4 class="modal-title">New employee</h4>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<!-- Modal body -->
<div class="modal-body py-2">
<div *ngIf="isSuccess" class="text-center alert alert-success">
Employee added successfully!
</div>
<div class="position-relative mb-1">
<label class="form-label" for="firstName">First name</label>
<input type="text" class="form-control" name="firstname" id="firstName" placeholder="First name" [(ngModel)]="firstname" #first_name="ngModel" required/>
<div *ngIf="first_name.touched && first_name.errors?.['required']" class="invalid-feedback">First name is required.</div>
</div>
...
(other form elements)
...
<div class="position-relative mb-1">
<label class="form-label" for="department">Department</label>
<select class="form-select" name="department" id="department" [(ngModel)]="deptno" #emp_department="ngModel" required>
<option value="-1">Pick a department</option>
<option *ngFor="let department of departments" [value]="department.value">
{{department.label}}
</option>
</select>
<div *ngIf="emp_department.touched && emp_department.value == -1" class="invalid-feedback">You must pick a department</div>
</div>
...
(remaining form elements)
...
</div>
<!-- Modal footer -->
<div class="modal-footer py-2">
<button type="submit" class="btn btn-success" [disabled]="!employeeForm.valid">Add employee</button>
<button type="button" class="btn btn-danger" data-bs-dismiss="modal">Cancel</button>
</div>
</form>
Moreover, in the employee-form.component.ts
file, there is a method named validateDepartment(form: NgForm)
, but it seems to be failing to validate correctly.
The main objective
The primary goal here is to ensure that a message saying "You must pick a department" appears over the select dropdown if no department is selected. Additionally, the form should remain invalid until a department is selected.
To address this issue, I have tried implementing the following solutions without success:
public validateDepartment(form: NgForm) {
if (this.deptno == -1) {
form.invalid;
}
}
public validateDepartment(form: NgForm) {
if (this.deptno != -1) {
form.valid;
}
}
You can check out a Stackblitz demo HERE.
Queries
- Why does the form appear valid while the select element remains invalid?
- What is the most effective way to resolve this issue?