首页 文章

Angular reactive Form错误:必须为表单控件提供一个名称为:

提问于
浏览
0

我的前提是我非常有角度的新手 . 我试图实现一个角度反应形式,但我遇到这个错误:“必须为名称为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
        });

    }

HTML:

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

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

1 回答

  • 0

    可能会出现错误,因为 this.flightChoice.DestinationId === undefined 并且您尝试将 undefined 设置为表单上的 Destination 字段 .

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

相关问题