raghav
raghav

Reputation: 63

how to bind mat-select with dynamic data from api

when making async call to api and trying to bind data from api to mat-select control it is not binding bcoz mat-select has already been set while the results are fetched after sometime. Can anyone tell me how to fix this

app.component.html

<mat-select appearance=fill>
      <mat-option *ngFor="let city of data | async " [value]="city">{{city}}</mat-option>
    </mat-select>

in app.component.ts

export class AppComponent implements AfterViewInit {
 
  dataarr: string[] = [];
  
  constructor() {

    this.getDatafromURL(this.dataarr, 'http://localhost:8080/geoserver/tutorial/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=tutorial%3Adistrict&maxFeatures=50&outputFormat=application%2Fjson')
         
  }
  getDatafromURL(data:string[],url:string) {
     
    fetch(url).then(function(response){
      response.json().then(function(result){
        let features = result.features;
        
        features.forEach((element: { properties: { NAME_2: any; }; }) => {
          data.push(element.properties.NAME_2)
        });
        
      })
      
    })
    
  }

Upvotes: 1

Views: 3110

Answers (1)

mojtaba ramezani
mojtaba ramezani

Reputation: 1559

try this:

ngOnInit(): void {
  this.countryList$ = this.getCountries();
}

getCountries(): Observable<ICountry> {
 return this.http.get<ICountry> 
 ('https://jsonplaceholder.typicode.com/posts');
}

in ts file:

<ng-container *ngIf="countryList$ | async as countryList">
    <mat-select>
      <mat-option *ngFor="let country of countryList 
        [value]="country">                  
        {{country.name}}
   </mat-option>
 </mat-select>
</ng-container>

Upvotes: 2

Related Questions