2017-10-06 123 views
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; 
     } 
    } 
    } 
+0

使用ngModel像[(ngModel)] =」 newTrip.from.city「 – Chandru

+0

我也試過......這是我的第一個選擇。沒有工作 – Miguel

+0

你也可以使用接口並執行如下操作:https://stackoverflow.com/a/43788669/6294072 – Alex

回答

0

你必須知道:newTrip[from]undefined,這就是爲什麼你不能從它得到城市。 作爲解決方案,您可以創建一個包含一個類名爲地點:

class Place{ 
    city: string; 
    country: string; 
    lat: number; 
    lng: number; 
} 

,並在你的班級旅行:

from: Place = new Place(); 
to : Place = new Place(); 

希望它可以幫助你