angular2 - 在表单中创建一个新的嵌套对象

时间:2017-10-06 15:04:15

标签: forms angular object nested

在我的Angular2网页中渲染表单时出现以下错误。该组件用于创建新的嵌套对象,因此是一个空表单。

问题出现在对象的嵌套参数中。 departureDate正好在trip(trip.departureDate)之下,因此它可以在浏览器中运行。因为" city"嵌套在"来自" (newTrip.from.city)我收到错误:

  

错误类型错误:无法读取属性' city'未定义的       在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&#34; newTrip&#34;使用&#34; Trip&#34;模型):

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;
        }  
    }
  }

1 个答案:

答案 0 :(得分:0)

你必须知道:newTrip[from]undefined,这就是为什么你无法从中获取城市的原因。 作为解决方案,您可以创建一个名为Place的类,其中包含:

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

并在你的班级旅行中:

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

希望它可以帮到你