programing

각도 반응 양식 오류:폼 제어에 대한 값을 다음 이름으로 제공해야 합니다.

oldcodes 2023. 8. 2. 09:23
반응형

각도 반응 양식 오류:폼 제어에 대한 값을 다음 이름으로 제공해야 합니다.

저는 제가 각진 초보자라고 가정합니다.각 반응 폼을 구현하려고 하는데 다음 오류가 발생했습니다. "폼 제어 값을 이름으로 제공해야 합니다.목적지.

다음은 내 구성 요소와 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>
            <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>

CreateForm 메서드에서 잘못된 내용을 쓰고 있지만 값을 할당하는 방법을 잘 모르겠습니다.

사용 중인 경우 이 오류가 나타날 수 있습니다.setValue에서formGroup해당 그룹 내의 모든 컨트롤에 대한 값을 전달하지 않습니다.예:

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

그룹의 일부 컨트롤만 업데이트하려면 다음을 사용할 수 있습니다.patchValue대신:

group.patchValue({foo: 'only foo, no problem!'});

문서:setValue그리고.patchValue 여기서

유감스럽게도 '정의되지 않음'은 허용되지 않습니다. 각 속성을 'null'로 설정해야 합니다.

호출하기 전에 속성을 변환할 수 있습니다.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);

조심하세요 왜냐하면JSON.stringify()제거할 것입니다.undefined따라서 서버로 값을 다시 보내는 데 사용할 경우 서버가 누락된 속성을 처리할 수 있는지 확인해야 합니다.


다른 방법으로, 이것은 무엇보다도 자바스크립트 팁입니다.

속성을 설정할 때 사용하여 속성이 null인지 확인할 수 있습니다.경우에 따라 도움이 될 수 있습니다.

예를 들면

form.setValue({

   firstName: firstName ?? null,    // null if firstName === undefined
   lastName: lastName ?? null

})

이것은 사용하기에 유리합니다.||숫자 형식 값(및 형식 값은 임의의 유형일 수 있음) 때문입니다.0이것에 의해 전멸할 것입니다. (이후로.0 || null=>null그리고 아닌0).

아마도 다음과 같은 이유로 오류가 나타날 것입니다.this.flightChoice.DestinationId === undefined그리고 당신은 설정하려고 노력합니다.undefined에게Destination필드를 입력합니다.

api가 데이터를 올바르게 다운로드하고 있는지 확인합니다.this.flightChoice.

언급URL : https://stackoverflow.com/questions/51047540/angular-reactive-form-error-must-supply-a-value-for-form-control-with-name

반응형