Search code examples
angularangularfire

I'm not able to add data into the dropdown


I have data called categories. I'm able to fetching the data from firebase however I'm having some problems while adding the data to dropdown. I can see the data on the console. I get the data through Firebase.

.html

<div class="container mt-5">
  <div class="row justify-content-center">
   <div class="col-6">
        <h5>Choose Category</h5>
        <select class="form-select" >
          <option *ngFor="let category of categories">{{category?.name}} 
          </option>
        </select>
   </div>
  </div>
 </div>

.ts

export class ProfileUpdateTwoComponent implements OnInit {

  categories: Category[] = []

  constructor(public realtime: RealtimeService) { }

  ngOnInit() {
    this.listCategory()
    console.log(this.categories)
  }

   listCategory(){
      this.realtime.listCategory().snapshotChanges().subscribe(data=>{
      data.forEach(k=>{
        const x = { ...k.payload.toJSON(), key:k.key}
        this.categories.push(x as Category)
      })
    })
  }

}

Console HTML


Solution

  • You may need to add in the async pipe to your ngFor statement. Are you receiving any errors in your console?

    <option *ngFor="let category of categories | async">{{category?.name}} 
    </option>
    

    I would also recommend importing Observable from rxjs

    import { Observable } from 'rxjs';
    

    and then update your categories object to the following

    categories: Observable<Category[]>;
    

    then add the async pipe to your *ngFor loop.