角反应形式错误:必须为名称为表单的控件提供值:

use*_*784 5 forms typescript angular

我以为我是新手。我正在尝试实现角度反应形式,但遇到此错误:“必须为名称为Destination的形式控件提供一个值。

这是我的组件和html的相关部分:

import { Component, Inject } from '@angular/core';
import { Http } from "@angular/http";
import { FormGroup, FormControl, FormBuilder, Validators } from "@angular/forms";

@Component({
    selector: 'home',
    templateUrl: './home.component.html'
})
export class HomeComponent {

    locations: Location[];
    flightChoice: FlightChoice;
    form: FormGroup;


    constructor(http: Http, @Inject('BASE_URL') private baseUrl: string,
        private fb: FormBuilder) {

        this.createForm();

        http.get(baseUrl + 'api/FlightChoice/dest_locations').subscribe(result => {
            this.locations = result.json() as Location[];
            console.log(this.locations);

        }, error => console.error(error));

        http.get(baseUrl + 'api/FlightChoice/choice').subscribe(result => {
            this.flightChoice = result.json() as FlightChoice;
            this.updateForm();
        }, error => console.error(error));

    }

    createForm() {
        this.form = this.fb.group({
            Destination: [0],
            NrPasg: [1],
            TwoWays: [false],
            DepartureDate: ['', Validators.required],
            ReturnDate: ['', Validators.required]
        });
    }

    updateForm() {

        this.form.setValue({
            Destination: this.flightChoice.DestinationId,
            NrPasg: this.flightChoice.NrPasg,
            TwoWays: this.flightChoice.TwoWays,
            DepartureDate: this.flightChoice.DepartureDate,
            ReturnDate: this.flightChoice.ReturnDate
        });

    }
Run Code Online (Sandbox Code Playgroud)

的HTML:

<form [formGroup]="form" (ngSubmit)="onSubmit()">
        <div>
            <label for="destination">Destination:</label>
            <br />
            <select id="destination" formControlName="Destination">
                <option *ngFor="let location of locations" value="{{ location.id }}">
                    {{ location.name }}
                </option>
            </select>
            <br />
            <label for="nrPasg">Number of Passengers:</label>
            <br />
            <input formControlName="NrPasg" type="number" id="nrPasg" value="1" />
            <label for="twoWays"></label>
            <br />
            <select id="twoWays" formControlName="TwoWays">
                <option value="false">one way</option>
                <option value="true">two ways</option>
            </select>
            <br />
            <label for="departureDate">Departure Date:</label>
            <br />
            <input formControlName="DepartureDate" type="date" id="departureDate" />
            <br />
            <label for="returnDate">Return Date:</label>
            <br />
            <input formControlName="ReturnDate" type="date" id="returnDate" />

        </div>
        <div>
            <button type="submit">Search Flights</button>

        </div>
    </form>
Run Code Online (Sandbox Code Playgroud)

我知道我可能在CreateForm方法中写了一些错误,但是我不确定如何分配值

ada*_*ort 82

如果你正在使用可能会出现此错误setValueformGroup,但在价值没有通过该组中的每个控件。例如:

let group = new FormGroup({
  foo: new FormControl(''), 
  bar: new FormControl('')
});
group.setValue({foo: 'only foo'}); //breaks
group.setValue({foo: 'foo', bar: 'bar'}); //works
Run Code Online (Sandbox Code Playgroud)

如果您真的只想更新组上的某些控件,则可以patchValue改用:

group.patchValue({foo: 'only foo, no problem!'});
Run Code Online (Sandbox Code Playgroud)

setValue这里的文档patchValue


Sim*_*ver 10

不幸的是,不允许使用“未定义”,您需要将每个属性设置为“空”。

您可以在调用之前转换属性,setValue如下所示:

   // set all 'missing' OR 'undefined' properties to null
   const newValue: any = {...value};

   for (const field in this.controls) { 

       if (newValue[field] === undefined) {
           newValue[field] = null;
       }
   }

   super.setValue(newValue, options);
Run Code Online (Sandbox Code Playgroud)

注意 因为JSON.stringify()will remove undefined,因此如果您使用它来将值发送您的服务器,您需要确保它可以处理那里丢失的属性。

  • 当我有机会时,我想提出一个新选项 `allowUndefined`,它允许将所有 `undefined` 属性视为 `null`。还有 `allowMissing` 允许缺少属性,并将缺少的属性设置为 null。 (2认同)

amb*_*ssh 6

可能出现此错误是因为this.flightChoice.DestinationId === undefined,您尝试设置undefinedDestination表单上的字段。

检查api是否正确将数据下载到this.flightChoice