Home > Mobile >  "onChange" event not firing in component, html Angular
"onChange" event not firing in component, html Angular

Time:05-05

I have this html template for a component that renders all the doctors in the database, and an array of colors as a dropdown list. when a value is chosen from the dropdown color list, the onChange event should fire, and call a function that sends a query to the database and change the value accordingly. the problem is that the onChange event is not firing, neither the onclick.

here is the code:

<table id="colorsTable" border="2">
<tr>
  <th>Doctor</th>
  <th>Color</th>
  <th>New Color</th>
</tr>
<tr *ngFor="let doctor of doctors">
  <td>{{ doctor.fullname }}</td>
  <td>
    {{ doctor.color }}
  </td>
  <td>
    <select>
      <option
        *ngFor="let color of colors"
        [ngStyle]="{ backgroundColor: color }"
        (change)="changeColor($event)"
      >
        {{ color }}
      </option>
    </select>
  </td>
</tr>

here is the component.ts file:

import {
Component,
Injectable,
EventEmitter,
NgModule,
OnInit,
Output,
} from "@angular/core";
import { element } from "protractor";
import { DoctorsService } from "../../../../../services/doctors.service";

@Component({
    selector: "doctor-color-settings",
    templateUrl: "./doctor-color-settings.component.html",
    styleUrls: ["./doctor-color-settings.component.scss"],
})
@Injectable()
export class DoctorColorSettingsComponent {
  public doctors: Array<any> = [];
  public colors: Array<any> = [
   "IndianRed",
   "LightCoral",
   "Salmon",
   "DarkSalmon",
   "LightSalmon",
   "Crimson ",
   "Red",
   "FireBrick",
   "DarkRed",
   "Pink",
   "LightPink",
   "HotPink",
   "DeepPink",
   "MediumVioletRed",
   "PaleVioletRed",
 ];
 constructor(private doctorsService: DoctorsService) {
  this.getDoctorsIntoTable();
 }

 private getDoctorsIntoTable() {
  this.doctorsService.getAllDoctors().then((res) => {
    if (!(res === null || (Array.isArray(res) && res.length === 0))) {
      this.doctors = res;
    }
  });
 }

changeColor(event: any) {

  alert("onchange event fired");
}

}

CodePudding user response:

Put your listener in the select element. Option elements don't have change listeners.

<select (change)="changeColor($event)">
      <option
        *ngFor="let color of colors"
        [ngStyle]="{ backgroundColor: color }"
        >
        {{ color }}
      </option>
    </select>
  • Related