在Angular中更新类型为date的表单值

时间:2018-06-27 09:30:39

标签: angular forms date

我有一个响应式表单,我正在尝试通过代码更新其字段:

updateForm() {
         console.log(this.flightChoice.departureDate);
         this.form.controls["Destination"].setValue(this.flightChoice.destinationId);
         this.form.controls["NrPasgs"].setValue(this.flightChoice.nrPasgs);
         this.form.controls["TwoWays"].setValue(this.flightChoice.twoWays);
         this.form.controls["DepartureDate"].setValue(this.flightChoice.departureDate);
         this.form.controls["ReturnDate"].setValue(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>
            <div *ngIf="hasError('Destination')" class="help-block">
                Destination is a required field: please insert a valid text
            </div>
            <br />
            <label for="nrPasgs">Number of Passengers:</label>
            <br />
            <input formControlName="NrPasgs" type="number" id="nrPasgs" value="1" />
            <div *ngIf="hasError('NrPasgs')" class="help-block">
                Nr Passengers is a required field: please insert a valid text
            </div>
            <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" />
            <div *ngIf="hasError('DepartureDate')" class="help-block">
                DepartureDate is a required field: please insert a valid text
            </div>
            <br />
            <label for="returnDate">Return Date:</label>
            <br />
            <input formControlName="ReturnDate" type="date" id="returnDate" />

        </div>
        <div>
            <button type="submit"  [disabled]="form.invalid">Search Flights</button>

        </div>
    </form>

当我更新日期控件时,什么也没发生,日期没有写在控件中。 (我猜是因为我在输入框中看到的是dd / mm / yyyy时传递了另一种日期格式yyyy / mm / dd)。日期控件也有带有日历的日期选择器,这很好,但是我想更新日期的默认值。 从api控制器中检索了FlightChoice对象,并在控制台中验证了传递的日期正确。

0 个答案:

没有答案