Home > Software engineering >  ngFor is not populating values properly
ngFor is not populating values properly

Time:09-27

I am trying to populate the dropdown with the values from the database now when I am trying using ngFor inside the ul tag it's only showing the first value but it should show me two values because I have two values in the DB and also the GET request is giving me an array of size 2. So I tried to keep the ngFor in the some other tag, then it's giving me two values but everything is coming in 2 numbers as the for loop is working it's replicating everything.

template

<div class="dropdown">
  <button (click) = "dd()" class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
    Select Doctor
  </button>
  <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1" *ngFor="let d of doctor">
    <li><a class="dropdown-item" href="#">{{d.name}}</a></li>
  </ul>
</div>

component.ts

  patientForm: FormGroup;
  doctor: Doctor[];

  constructor(private doctorService: DoctorService) { }

  ngOnInit(): void {
    this.patientForm = new FormGroup({
      name: new FormControl('', [Validators.required]),
      illness: new FormControl('', [Validators.required]),
      // doctorId: new FormControl('', [Validators.required])
    })
    this.doctorService.getDoctor().subscribe(data=>{
      this.doctor = data;

      // checking if the data is coming and going into the array
      console.log(this.doctor);
    })
  }

here's what I am getting in the console

  (2) [{…}, {…}]
  0: {id: 1, name: "Dr.Subhajit", degree: "MD", specialization: "Heart"}
  1: {id: 2, name: "Dr.Tamanash", degree: "MD", specialization: "Brain"}
  length: 2
  __proto__: Array(0)

And here's my service

  private getApi: string = 'http://localhost:8080/doctor'
  constructor(private http: HttpClient) { }

  public getDoctor() : Observable<Doctor[]>{
    return this.http.get<Doctor[]>(this.getApi);
  }

CodePudding user response:

Your example works just fine for me when I hard-code an array of 2 doctors.

See my example on stackblitz.

However, I would move the *ngFor to the <li> element. Right now you are creating multiple unordered lists.

The problem must be in your service somewhere, or in the backend.

Try printing the data you are getting from the service:

this.doctorService.getDoctor().subscribe(data=>{
  console.log(data);
  this.doctor = data;
})

And see what you are getting back from the service in your browser dev tools.

  • Related