在Angular 2模型驱动的表格中下拉列表 [英] Drop Down List in Angular 2 Model Driven Form

查看:111
本文介绍了在Angular 2模型驱动的表格中下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型驱动的表单,我想添加一个包含多个选项的下拉列表。选项来自预取列表,表单的模型被注入到组件中。表单被正确加载:模型中的所有字段都被正确填充,abd下拉列表的选项列表也被正确加载。

唯一的问题是我无法设置选中列表的值,并且它首先显示为空值。

I have a model driven form in which I would like to add a drop down list containing several options. The options are from a pre-fetched list, and the model of the form is injected to the component. The form is loaded correctly: All the fields from the model are filled properly, abd the list of options for the drop-down list is also loaded correctly.
The only problem is that I can't set the selected value of the list, and it appears with an empty value at first.

这里,我加载HMOs列表,然后加载病人,然后才创建表单。

表单中的所有值(名称,ID等)均正确加载到表单中。

表单中的下拉列表填写正确:所有HMO正在填充列表。

仍然,列表中的选定值缺失,并且丢失的内容没有初始值。
出于调试目的,我已经替换选项标签中的布尔条件: patient.hmo.uid == hmo .uid 函数调用: isSelected(hmo)

这个函数实质上做了相同的比较并返回它的值,但冷杉t记录它。事实上,我发现具有正确hmo的选项获得 true 值,而其他所有选项获得 false 值,这意味着所有数据加载正确。

Here, I am loading the HMOs list, then loading the patient, and only then creating the form.
All the values of the form (name, id, etc. which are omitted here) are loaded correctly into the form.
The drop-down list in the form is filled correctly: All HMOs are populating the list.
Still, the selected value in the list is missing, and the lost is loaded with no initial value.
For debugging purposes, I have replaced the boolean condition in the option tag: patient.hmo.uid == hmo.uid to a function call: isSelected(hmo).
This function essentially does the same comparison and returns its value, but first logs it. Indeed I see that the option with the correct hmo gets a true value and all other options get false values, meaning all data is loaded correctly.

另外,当我设置 [selected] =true(总是为true),我确实看到了变化影响:最后一个选项被选中(默认为HTML)。

Also, when I set the [selected]="true" (always to be true), I do see the change affects: The last option is selected (the default in HTML).

我错在哪里?

So where am I wrong? How should I set the selected option correctly?

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

Code for the component (all fields except HMO are omitted):

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表单的代码:

Code for the HTML form:

<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){}
}


推荐答案

通过比较< option> 的值与< select> 的值。鉴于此,要将< option> 标记为选中状态,我们需要确保包装< select> 包含相同的值,这又需要模型中相应表单控件的正确值。

The selected option is calculated by comparing the <option>'s value with <select>'s value. In light of that, to mark an <option> as selected, we need to make sure the wrapping <select> is containing the same value, which in turn requires the correct value of the corresponding form control in your model.

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

Your code can be slightly modified as follow:

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

和模板:

And Template:

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

这篇关于在Angular 2模型驱动的表格中下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆