Home > OS >  Create a FormControl for a `mat-select`
Create a FormControl for a `mat-select`

Time:11-15

I have a reactive form that, among other input fields, it also includes a <mat-select> and I've managed to create FormControls for the other input fields, except for this one. I'm trying to retrieve some values which have already been provided in the service (where I created an array of sample appointments) and link them to the corresponding fields of the form - all of them are working fine, but I'm failing to do so for the <mat-select>, as it can be observed in the following image:

enter image description here

In addition, for clarification, speciality, appointmentDate, doctorName & notes all belong to the appointment-model.

Any advice would be of great help as I'm a beginner in the field, thanks!

doctors = [{
    value: 'doctor-0',
    viewValue: 'Amy Holmes'
  },
  {
    value: 'doctor-1',
    viewValue: 'Susan Pierce'
  },
  {
    value: 'doctor-2',
    viewValue: 'Derek Smith'
  },
];
private initForm() {
  let appointmentSpeciality = '';
  let appointmentDate = new Date(0);
  let appointmentDoctorName = '';
  let appointmentNotes = '';
  if (this.editMode) {
    const appointment = this.appointmentService.getAppointment(this.id);
    appointmentSpeciality = appointment.speciality;
    appointmentDate = appointment.appointmentDate;
    appointmentDoctorName = appointment.doctorName;
    appointmentNotes = appointment.notes;
  }
  this.appointmentForm = new FormGroup({
    speciality: new FormControl(appointmentSpeciality),
    appointmentDate: new FormControl(appointmentDate),
    doctorName: new FormControl(appointmentDoctorName),
    notes: new FormControl(appointmentNotes),
  });
}
<mat-form-field  appearance="fill">
  <mat-label>Choose a doctor</mat-label>
  <mat-select name="doctor" formControlName="doctorName">
    <mat-option>None</mat-option>
    <mat-option *ngFor="let doctor of doctors" [value]="doctor.value">
      {{ doctor.viewValue }}
    </mat-option>
  </mat-select>
</mat-form-field>

CodePudding user response:

For sure, you have the appropriate handling for mat-select component and formControlName directive. If all besides it works I suppose that appointment.doctorName has assigned another value than 'doctor-0' or 'doctor-1' or 'doctor-2'.

Please verify it because with hardcoded key, it's working https://stackblitz.com/edit/angular-zvkd1u?file=src/app/select-form-example.ts

  • Related