角度:更改选择选项

时间:2018-07-09 19:54:14

标签: angular typescript

我有一个带有多个选择的表格。

  • 选择1:校园
  • 选择2:建筑
  • 选择3:楼层
  • 选择4:房间

从“校园”中选择一个选项后,我希望建筑物列表发生更改(从数据库更新)。下游选择同样。

这是我到目前为止的内容...我可以填充每个选择,但是我不知道如何在原位动态更新它们。

form.component.html

<form [formGroup]="campusForm">
    <select id="campus" formControlName="campus" [ngModel]="null" (ngModelChange)="selectCampus($event)>
        <option [ngValue]="null" selected="selected">All Campuses</option>
        <option [ngValue]="campus" *ngFor="let campus of campuses"> {{campus.name}}</option>
    </select>

    <select id="building" formControlName="building" [ngModel]="null" (ngModelChange)="selectBuilding($event)>
        <option [ngValue]="null" selected="selected">All Buildings</option>
        <option [ngValue]="building" *ngFor="let building of buildings"> {{campus.name}}</option>
    </select>

    <!-- etc... -->
</form>

form.component.ts

ngOnInit() {
  this.loadCampuses();
  this.loadBuildings();
  //...
}

loadCampuses() {
  this.campusService.getCampuses().subscribe((res: Campus[]) => {
    this.campuses = res;
  });
}

selectCampuses(campus: Campus) {
  console.log (campus ? campus.name : "all campuses")
  this.loadBuildings(campus);
}

loadBuildings(campus: Campus) {
  this.buildingService.getBuildings(campus).subscribe((res: Building[]) => {
    this.buildings = res;
  });

  this.updateBuildingsSelect()
}

updateBuildingsSelect() {
  // This is where I'm stuck
}

1 个答案:

答案 0 :(得分:0)

请勿访问[ngModel]="null"。这样,无论什么情况,您都只是将其值设为null。而是用一些有意义的值填充它。例如:

form.component.ts

selectedCampus: Campus = null;
selectedBuilding: Building = null;

selectCampus(campus: Campus) {
    this.selectedCampus = campus;
}

selectBuilding(building: Building) {
    this.selectedBuilding = building;
}

form.component.html

<select [ngModel]="selectedCampus">...</select>
<select [ngModel]="selectedBuilding">...</select>