角度更新下拉列表

时间:2019-03-07 12:10:01

标签: angular typescript angular7

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

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

}

City.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>

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

1 个答案:

答案 0 :(得分:1)

我可能需要查看您的整个项目来找出问题所在,但是我在这个堆叠闪电战中做了类似的事情:

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

有效。