【问题标题】:Call method when select option changed? (Angular)选择选项更改时的调用方法? (角度)
【发布时间】:2020-08-12 01:37:31
【问题描述】:

我有一个带有 WebApi 后端的 Angular 应用程序。在选择元素中,我显示了一些城市名称。当我选择一个城市时,我想在表格中显示该城市的街道。

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;
    })
  }
}

getCities() 方法填充选择元素。使用 getStreetsOfCity() 方法,我想获取所选城市的街道。

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>

这是服务中的方法:

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

我的控制台没有返回任何内容,也没有显示任何内容,我真的不知道为什么。你们有人有什么想法吗?

【问题讨论】:

    标签: angular typescript ionic-framework


    【解决方案1】:

    您只需像这样将(change) 事件添加到您的select 元素中

    <h1>Warenlieferungen</h1>
    <br>
    <p>Stadt:</p>
    <select [(ngModel)]="selectedCity" (change)="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>
    

    【讨论】:

    • 没问题。随意提出任何 Angular 问题。谢谢
    猜你喜欢
    • 1970-01-01
    • 2015-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-25
    • 2015-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多