0
在我的Angular2 Web中呈現表單時出現以下錯誤。這個組件用於創建一個新的嵌套對象,因此是一個空的表單。angular2 - 在表單中創建一個新的嵌套對象
該問題出現在對象的嵌套參數中。出發日期正好在trip(trip.departureDate)之下,因此它在瀏覽器中工作。由於 「城市」 嵌套在 「從」(newTrip.from.city)我得到的錯誤:
ERROR TypeError: Cannot read property 'city' of undefined at Object.eval [as updateDirectives]
HTML:
<h3>NEW TRIP </h3>
<div class="field">
<h6>Departure: </h6>
<input ngui-datetime-picker name="departureDateTime" [(ngModel)]="newTrip.departureDateTime" required>
</div>
<div class="field marginTop">
<h6>From: </h6>
<label for="newTrip">City: </label>
<input type="text" name="fromcity" [(ngModel)]="newTrip[from].city" required>
<label for="newTrip">Country: </label>
<input type="text" name="fromCountry" [(ngModel)]="newTrip[from].country" required>
</div>
<div class="field marginTop">
<h6>Arrival: </h6>
<input ngui-datetime-picker name="arrivalDateTime" [(ngModel)]="newTrip.arrivalDateTime" required>
</div>
component.ts(我初始化VAR 「newTrip」 與在 「旅行」 模式):
export class NewTripComponent implements OnInit {
newTrip: Trip = new Trip();
error: string;
行程型號:
export class Trip {
_id: string;
owner: string;
from: {
city: string;
country: string;
lat: number;
lng: number;
};
to: {
city: string;
country: string;
lat: number;
lng: number;
};
departureDateTime: Date;
arrivalDateTime: Date;
bag: {
restrictions: Array<string>;
weight: number;
dimensions: {
high: number;
width: number;
}
}
}
使用ngModel像[(ngModel)] =」 newTrip.from.city「 – Chandru
我也試過......這是我的第一個選擇。沒有工作 – Miguel
你也可以使用接口並執行如下操作:https://stackoverflow.com/a/43788669/6294072 – Alex