Angular 2模型驱动表格中的下拉列表

时间:2016-09-25 16:15:58

标签: html forms angular

我有一个模型驱动的表单,我想在其中添加一个包含多个选项的下拉列表。选项来自预先获取的列表,并且表单的模型被注入到组件中。表单已正确加载:模型中的所有字段都已正确填充,而下拉列表的选项列表也正确加载。
唯一的问题是我无法设置列表的selected值,并且它最初显示为空值。

在这里,我正在加载HMOs列表,然后加载患者,然后才创建表单 表格的所有值(名称,id等在此省略)都正确加载到表格中 正确填写表单中的下拉列表:所有HMO都填充列表 仍然,列表中的选定值丢失,丢失的内容没有初始值 出于调试目的,我已将option标记中的布尔条件:patient.hmo.uid == hmo.uid替换为函数调用:isSelected(hmo)
此函数基本上执行相同的比较并返回其值,但首先记录它。实际上,我看到具有正确hmo的选项获得true值,所有其他选项获得false值,这意味着所有数据都已正确加载。

此外,当我设置[selected]="true"(总是为真)时,我确实看到更改有效:选择了最后一个选项(HTML中的默认选项)。

那我错在哪里?我该如何正确设置所选选项?

组件的代码(省略除HMO之外的所有字段):

import {Component, Input, Inject, OnInit} from "@angular/core";
import {
  FormGroup,
  FormControl,
  REACTIVE_FORM_DIRECTIVES,
  Validators,
  FormBuilder,
  FormArray
} from "@angular/forms";
import {Patient} from "./patient";
import {PatientsService} from "./patients.service";
import {Hmo} from "../hmos/hmo";
import {HmosService} from "../hmos/hmos.service";
import {Doctor} from "../doctors/doctor";
import {DoctorsService} from "../doctors/doctors.service";
import {Router, ActivatedRoute} from "@angular/router";
import {Subscription} from "rxjs/Rx";
import {Response} from "@angular/http";
import {JavaDate} from "./java-date";

@Component({
  moduleId: module.id,
  selector: 'gy-patient-edit',
  templateUrl: 'patient-edit.component.html',
  directives: [REACTIVE_FORM_DIRECTIVES],
})
export class PatientEditComponent implements OnInit {

  patientForm: FormGroup;

  @Input() patient: Patient;
  private hmos: Hmo[];
  private patientUid: number;
  private showForm: boolean = false;

  constructor(@Inject(PatientsService) private patientsService: PatientsService,
              @Inject(HmosService) private hmosService: HmosService,
              @Inject(ActivatedRoute) private route: ActivatedRoute,
              @Inject(FormBuilder) private formBuilder: FormBuilder) {
  }

  ngOnInit(): any {
    this.subscription = this.route.params.subscribe(
      (params: any) => {
        this.patientUid = params['id']; //Getting the UID from the URL
      }
    );
    this.hmosService.hmosChanged.subscribe(
      (hmos: Hmo[]) => {
        this.hmos = hmos; //Fetching available HMOs
      }
    );
    this.hmosService.fetchHmos();
    this.patientsService.fetchPatient(this.patientUid) //Fetching the Patient
      .map((response: Response) => response.json())
      .subscribe((data: Patient) => {
        this.patient = data;
        this.restartForm(); //Only required so the form will ne initialized only after the patient is received from the server
      });
  }

  restartForm(){
    this.patientForm = this.formBuilder.group({
      hmo: [this.patient.hmo]]
    });
    this.showForm = true;
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

}

HTML表单的代码:

<div class="row" *ngIf="showForm">
  <div class="col-xs-12" *ngIf="showForm">
    <form [formGroup]="patientForm" (ngSubmit)="onSubmit()">
      <div class="form-group">
        <label for="hmo">HMO</label>
        <select formControlName="hmo" id="hmo">
          <option *ngFor="let hmo of hmos"
                  [value]="hmo.uid" [selected]="patient.hmo.uid == hmo.uid">
            {{hmo.name}}
          </option>
        </select>
    </form>
  </div>
</div>

Patient的代码:

import {Hmo} from "../hmos/hmo";
export class Patient {
  constructor(public hmo: Hmo) {

  }
}

Hmo的代码:

export class Hmo{
  constructor(public uid: number, public name: string){}
}

1 个答案:

答案 0 :(得分:23)

通过将<option>的值与<select>的值进行比较来计算所选的选项。鉴于此,要将<option>标记为已选中,我们需要确保包装<select>包含相同的值,而这又需要模型中相应表单控件的正确值。

您的代码可以稍微修改如下:

  restartForm(){
    this.patientForm = this.formBuilder.group({
      hmo: [this.patient.hmo.uid]
    });
    this.showForm = true;
  }

和模板:

<select formControlName="hmo" id="hmo">
   <option *ngFor="let hmo of hmos"
     [value]="hmo.uid">
        {{hmo.name}}
   </option>
</select>