首页 > 解决方案 > Angular 6:基于其他下拉值的下拉显示选项

问题描述

我有 2 个下拉菜单,一个用于选择state,另一个用于service agent为服务机构显示的选项取决于所选的值。

服务机构和州下拉菜单的数据来自profile.service.ts.

问题:当用户选择状态时,如何使服务代理中的值显示发生变化。

profile.component.html

<mat-form-field>
    <mat-select placeholder="Service Agency" required formControlName="serviceAgency">
        <mat-option value="option">Option</mat-option>
        <mat-option value="{{item.id}}" *ngFor="let item of service_agency$">                     
            {{item.name}}  
        </mat-option>  
    </mat-select>
</mat-form-field>

profile.component.ts

//get state
get_state(){
    this.profileService.get_state().subscribe(data => {  
        this.state$ = data; 
    });  
}

//get service center base on state id
onChange(state) {
   this.service_agency$ = this.profileService.get_service_agency()
       .pipe(filter((item)=> item == state.value));

    console.log(this.service_agency$);
}

配置文件.service.ts

get_state() {
    return this.http.get(url)
        .pipe(map(data => {
            return data;
        }));
}

get_service_agency() {
    return this.http.get(url)
        .pipe(map(data => {
            return data;
        }));
}

标签: angularangular5angular6

解决方案


在 angular 中,当您更新任何数据时,它也会在 html 中反映该数据。

我猜当你改变 state 的值时,你调用 API 并获取service agency.

当您获得新列表时,您只需将该新列表绑定到变量中。Angular 会自动将该新列表绑定到 html 中。

<option *ngFor="let item of service_agency$" value=[item.name]>
    {{item.name}}        
</option>

更改状态值时:

onChange(state) {  // Get the ref of selected state 

  // Now hear you need to call API and pass state id and get new list of agency
  this.profileService.get_service_agency().subscribe((data) => {            

         // Clear all data from array and then bind new fresh data 
        this.service_agency$ = [];             // Clear 
        this.service_agency$.push(...data);    // Bind fresh data

        // Check data is bind in array properly or not ... 
        console.log("New service list data is ::: " , this.service_agency$);

  })
}

绑定新数据后,新列表会自动显示在HTML页面中。


推荐阅读