angular - Ionic Angular NgModel 错误引用接口(interface)中的子对象

标签 angular typescript firebase ionic-framework ionic3

这是我的界面:

booking.interface.ts

export interface Booking {
  "dateBooking": Date;
  "period": {
    "morning": boolean;
    "afternoon": boolean;
    "night": boolean;
  }
}

addbooking.ts

...
import { Booking } from '../../models/booking/booking.interface';
...
export class AddbookingPage {

  //declare a property of interface type
  public booking = {} as Booking;

   constructor() {
  }
...

当我尝试在 View 中引用 booking.period.morning 或对象期间的任何子属性时,Ionic 引发错误:

addbooking.html

  <ion-item>
    <ion-label>Morning</ion-label>
    <ion-checkbox [(ngModel)]="booking.period.morning"></ion-checkbox> 
  </ion-item>

错误:

TypeError: undefined is not an object (evaluating '_co.booking.period.morning')

我试图实现一个复选框并将数据保存在 Firebase 中。如果有任何其他方法可以实现这一点,我会接受建议。

最佳答案

您需要:

初始化你的对象以匹配你的界面

public booking: Booking = {
  dateBooking: new Date(),
  period: {
   morning: true,
   afternoon: false,
   night: false, 
  }  
}

或隐藏复选框,直到对象具有 period.morning 属性。

<ion-item>
  <ion-label>Morning</ion-label>
  <ion-checkbox *ngIf="booking && booking.period && typeof booking.period.morning === 'boolean'" [(ngModel)]="booking.period.morning"></ion-checkbox> 
</ion-item>

关于angular - Ionic Angular NgModel 错误引用接口(interface)中的子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49940645/

相关文章:

javascript - 循环遍历对象的关联数组

ios - 使用 Firebase 的应用程序在设备/模拟器上安装 3-4 天后崩溃 (iOS)

子组件中的 Angular @Input 也会更新父组件中的值

angular - 我不能在 Angular 6 的箭头上使用 Ngif

javascript - 关于 import 如何知道去 package.json 的解释

firebase - 由于Cloud Build API,Firebase Cloud Functions是否要求在2020年4月20日之前启用计费功能?

reactjs - 如何在 Google Cloud Firestore 中使用点表示法中的变量

angular - 如何定义外部库的类型。 TypeScript、Angular 和 Google Picker

javascript - 将两个数字与 typescript 相乘,读取 NaN

reactjs - 如何从包装 React 组件传入material-ui TextField 的变体属性