【问题标题】:Angular update dropdown list角度更新下拉列表
【发布时间】:2026-01-31 03:10:01
【问题描述】:

我有一个下拉列表(区域),它定义了下一个(城市)应该显示的内容

区域.ts

    @Component({
  selector: 'app-region-dropdown',
  templateUrl: './region-dropdown.component.html',
  styleUrls: ['./region-dropdown.component.css'],
  providers: [RegionService, CityDropdownComponent]
})
export class RegionDropdownComponent implements OnInit {
  regions: Array<Region>;

  constructor(private regionsService: RegionService, private cityDropDown: CityDropdownComponent) { }

  ngOnInit() {
    this.regionsService.getAll().subscribe(data => {
      this.regions = data;
    });
  }

  public onChange(value):void {
    console.log(value);
    this.cityDropDown.loadList(value);
  }

}

城市.ts

@Component({
  selector: 'app-city-dropdown',
  templateUrl: './city-dropdown.component.html',
  styleUrls: ['./city-dropdown.component.css'],
  providers: [RegionService]
})
export class CityDropdownComponent implements OnInit {

  cities: Array<City>;

  constructor(private regionsService: RegionService) { }

  ngOnInit() {

  }

  public loadList(regionId: number) {
    this.regionsService.getCities(regionId).subscribe(data => {
      console.log(data);
      this.cities = data;
    });
  }

}

city.html

<mat-form-field>
  <mat-select placeholder="City">
    <mat-option *ngFor="let city of cities" >
      {{city.name}}
    </mat-option>
  </mat-select>
</mat-form-field>

控制台显示 regionService 返回了一个列表,但城市列表从未更新

【问题讨论】:

  • 您确定返回的数据是针对城市而不是针对地区的吗?
  • 提供者中的CityDropdownComponent?
  • @GregoryMazur 使用共享服务在 onChange() 函数中传递值。使用共享服务和主题。
  • 先尝试将城市变量设置为一个空列表:city: Array = []; (在声明中)可能是没有对象的时候不能有onChange()事件。
  • 如果您在 StackBlitz 上遇到问题,我们可以尝试在那里解决。您的代码中没有明显的错误,但我看到有一些关于在 gihub 中动态更改 mat-select 可能会影响您的讨论。

标签: angular typescript angular7


【解决方案1】:

我可能需要查看您的整个项目以找出问题所在,但我在这个 stackblitz 上做了类似的事情:

https://stackblitz.com/edit/angular-7-master-wuuknx

有效。

【讨论】:

  • 大声笑,这很愚蠢,但我将代码转移到区域组件并且它可以工作
  • 顺便说一下我的例子,只是不知道该放什么来代替httpClient,这样它就可以在本地工作stackblitz.com/edit/angular-ihgbpg
  • 好的,您可能应该阅读与组件的交互。您有一个奇怪的组件 DI,没有任何意义,您还需要使用 Input 和 Output 指令将输入/输出传递给组件。看看你的解决方案的这个分支:stackblitz.com/edit/angular-whzhuh