【发布时间】:2019-01-07 21:16:33
【问题描述】:
我正在使用外部 API 来检索我正在开发的 Ionic 应用程序中的表单字段。然后我从这个表单中收集信息以创建一个新对象,该对象将被发送到 API 以进行记录。
其中一组字段(称为方法)的条目数可以是可变的,因此我已经能够使用 *ngFor= 指令显示字段。但是,我在尝试从这些中收集信息时遇到问题。这是我的代码:
来自 new-trip.html:
<ion-item>
<ion-label>Justification</ion-label>
<ion-select [(ngModel)]="newTrip.justification">
<ion-option *ngFor="let tripFieldJustification of tripFieldJustifications" value="{{tripFieldJustification.id}}">{{ tripFieldJustification.description }}</ion-option>
</ion-select>
</ion-item>
<ion-item-divider color="light">Travel Time</ion-item-divider>
<ion-item *ngFor="let tripFieldMethod of tripFieldMethods">
<ion-label floating>Hours travelled by {{ tripFieldMethod.method }} {{ tripFieldMethod.id }}</ion-label>
<ion-input type="text" type="number" [(ngModel)]="newTripHours[tripFieldMethod.id]" value="0"></ion-input>
</ion-item>
来自对应的new-trip.ts:
@Component({
selector: 'page-new-trip',
templateUrl: 'new-trip.html'
})
export class NewTripPage {
logOut: any;
tripFields: any;
tripFieldMethods: any = [];
tripFieldGenerals: any = [];
tripFieldPurposes: any = [];
tripFieldJustifications: any = [];
postAddType: any;
postPreviousPage: any;
newTrip: any = {};
newTripHours: any = {};
methods: any;
currentYear: any;
constructor(public navCtrl: NavController, public navParams: NavParams, public logOutService: LogOutService, public travelTrackerService: TravelTrackerService, public alertCtrl: AlertController) {
this.logOut = logOutService;
this.currentYear = new Date().getFullYear();
this.postAddType = navParams.get('addType');
this.postPreviousPage = navParams.get('previousPage');
travelTrackerService.getTripFields().then((response) => {
this.tripFields = response;
this.tripFieldMethods = this.tripFields['method'];
this.tripFieldGenerals = this.tripFields['general'];
this.tripFieldPurposes = this.tripFields['purpose'];
this.tripFieldJustifications = this.tripFields['justification'];
});
}
在下面的代码中,我可以毫无问题地将 justification 属性绑定到 newTrip.justification。但是我无法让“方法”输入字段绑定到任何对象,我不断收到以下错误:
NewTripPage.html:153 ERROR TypeError: Cannot read property '0' of undefined
at Object.eval [as updateDirectives] (NewTripPage.html:153)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:14697)
at checkAndUpdateView (core.js:13844)
at callViewAction (core.js:14195)
at execEmbeddedViewsAction (core.js:14153)
at checkAndUpdateView (core.js:13845)
at callViewAction (core.js:14195)
at execComponentViewsAction (core.js:14127)
at checkAndUpdateView (core.js:13850)
at callViewAction (core.js:14195)
我知道这个问题与数组有关。我怎样才能让这些动态变化的字段绑定到一个对象?
我对 Angular 很陌生,如果有人能提供帮助,我将不胜感激。谢谢。
【问题讨论】:
标签: angular typescript ionic-framework ionic3