如何在基于Angular2 Model的表单中从API填充下拉列表默认值

时间:2017-03-20 16:06:29

标签: angular typescript dropdown

我正在尝试在Angular2中创建一个基于模型的表单,其中包括从数据库中提取的几个下拉列表,然后将所选值绑定到表单。我需要能够在从以前保存的表单编辑表单的情况下初始化下拉值。我似乎无法找到任何直截了当的例子,只有将选定值绑定到全新表格的示例。以下是我到目前为止的情况:

组件:

import { Component, Input, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';
import { Http } from '@angular/http';
import { FormGroup, FormArray, FormControl, Validators, FormBuilder } from '@angular/forms';
import 'rxjs/add/operator/switchMap';

import { Part } from '../../models/part';
import { Series } from '../../models/series';

import { PartsService } from '../../services/parts.service';
import { SeriesService } from '../../services/series.service';

@Component({
selector: 'parts',
styleUrls: ['../../../styles/main.css'],
templateUrl: './partsForm.component.html',
providers: [PartsService, SeriesService]
})

export class PartsFormComponent implements OnInit{
@Input() part: Part;
selectedPart: Part;
partsForm: FormGroup;
partName = new FormControl();
series: Series;
seriesList: Series[];
seriesSearch: string;
selectedSeries: Series = new Series();
isEdit: boolean;
selected: any;




constructor(
    private partsService: PartsService,
    private seriesService: SeriesService,
    private route: ActivatedRoute,
    private location: Location,
    fb: FormBuilder
    ) {
    this.partsForm = fb.group({
        partName: new FormControl(''),
        partLength: new FormControl(''),
        seriesId: new FormControl(''),
});
}

ngOnInit(): void {
    let partId: string;

    this.route.params
        .subscribe((params: Params) => partId = params['id']);

    this.isEdit = (partId != undefined && partId.substring(0, 1) !== "T");

    if (this.isEdit) {
        this.partsService.getPartById(+partId).subscribe(part => this.part = part);
    }  else {
        this.part = new Part;
    }

    this.getSeriesList();
}

intializePartForm() {
    this.series.seriesId = this.part.seriesId;

}

getSeriesList() {
    this.seriesService.getAllSeries().subscribe(data => this.seriesList = data);
}

saveNew() {
    this.part.partId = 0;
    this.savePart();
}

savePart() {
    this.part.seriesId = this.selectedSeries.seriesId;

    this.partsService.savePart(this.part).subscribe(data => this.part = data);
}
}

HTML模板:

<form  *ngIf="part" [formGroup]="partsForm" (ngSubmit)="onSubmit()" >
    <div class="col-lg-6">        
        <div class="form-group" >
            <label>Part Name</label>
            <input type="text" class="form-control"  formControlName="partName" placeholder="Part Name" [value]="part.partName" [disabled]="isEdit">
        </div>
        <div class="form-group" >
            <label>Series</label>
            <select class="form-control" formControlName="series"> 
                <option *ngFor="let series of seriesList" [selected]="series.seriesId == part.seriesId" >{{series.seriesName}}</option>
            </select>
        </div>
        <div class="form-group">
            <label>Part Length</label>
            <input type="number" class="form-control"  formControlName="partLength" placeholder="Part Length" >
        </div>
        <div *ngIf="!isEdit">
            <button type="submit" class="btn btn-success" (click)="saveNew()" >Save As New</button>
        </div>
        <div *ngIf="isEdit">
            <button type="submit" class="btn btn-success" (click)="savePart()" >Save Changes</button>
        </div>
    </div>
</form>

模型 系列

export class Series {
    seriesId: number;
    seriesName: string;   
}

部分

export class Part {
        partId: number;
        partName: string;
        partLength: number;
        seriesId: number;
        seriesName: string;
}

1 个答案:

答案 0 :(得分:0)

在反应式表单中,[selected][disabled]之类的内容不起作用,您需要使用patchValue(或setValue)并切换启用和禁用字段另一种方式。

收到所需的数据后,请根据需要修改表单值。例如,在获得列表的值后,调用一个函数来设置值,这里名为patchForm()

getSeriesList() {
  this.seriesService.getAllSeries().subscribe(data => {
    this.seriesList = data;
    // call method here to set values
    this.patchForm();
  });
}

并且设置默认值的功能可能如下所示。您只需应用所需的逻辑而不是以下值。

patchForm() {
  this.partsForm.patchValue({
    partName: this.part.partName
    series: this.seriesList[1].seriesName
  })  
}

如上所述[disabled]在您的表单中无法工作(就像您正在尝试partName表单控件一样),您需要以其他方式切换启用和禁用。这可以通过以下方法实现:

toggleDisableEnable() {
  let control = this.partsForm.get('partName')
  control.enabled ? control.disable() : control.enable();
}

最后,......

Plunker

...修补你的形式帮助你:)你需要自己设置patchValue中的一些逻辑,只是给你一个如何做到这一点的例子,以及一个禁用和启用一个字段。