angulartypescriptionic-framework

Call method when select option changed? (Angular)


I have an Angular Application with an WebApi Backend. In a select-Element I show some city names. When I select one city I want to show the streets of this city in a table.

app.component.ts

export class AppComponent {
  title = 'ProbematuraFrontend';

  selectedCity:string;

  cities:City[]=[];
  streets:Street[]=[];

  constructor(private orderService:OrderService){}

  ngOnInit(): void {
    this.getCities();
  }

  getCities():void{
    this.orderService.getCities().subscribe(data=>{
      console.log(data);
      this.cities=data;
    });
  }

  getStreetsOfCity(selectedCity):void{
    this.orderService.getStreetnames(selectedCity).subscribe(data=>{
      console.log(data);
      this.streets=data;
    })
  }
}

The getCities() method fills the select-Element. With the getStreetsOfCity() method I want to get the streets of the selected city.

app.component.html:

<h1>Warenlieferungen</h1>
<br>
<p>Stadt:</p>
<select [(ngModel)]="selectedCity" class="form-control" style="width: 250px;height: 50px;">
  <option *ngFor="let city of cities" [ngValue]="city">{{city}}</option>
</select>

<table>
  <tr *ngFor="let street of streets">
    <td>{{street}}</td>
  </tr>
</table>


<router-outlet></router-outlet>

This is the method in the service:

public getStreetnames(selectedCity:string):Observable<Street[]>{
    return this.httpClient.get<Street[]>(`${this.host}Order/Streets/${selectedCity}`)
  }

I do not get anything back in my console and nothing is displayed and I do not really know why. Does someone of you have any ideas?


Solution

  • You just need to add (selectionChange) event to your select element like this

    <h1>Warenlieferungen</h1>
    <br>
    <p>Stadt:</p>
    <select [(ngModel)]="selectedCity" (selectionChange)="getStreetnames(selectedCity)" class="form-control" style="width: 250px;height: 50px;">
      <option *ngFor="let city of cities" [ngValue]="city">{{city}}</option>
    </select>
    
    <table>
      <tr *ngFor="let street of streets">
        <td>{{street}}</td>
      </tr>
    </table>