【问题标题】:Ionic 4 datetime picker does not update its variableIonic 4 日期时间选择器不更新其变量
【发布时间】:2019-01-30 12:00:59
【问题描述】:

我正在使用离子4 ion-datetime拾取器,尝试以表单选择日期,但选择新日期时,它不会更新变量。

我已尝试使用我知道的所有不同组合,但我已将所有这些组合都包含在此示例中。

<form [formGroup]="upsert" (ngSubmit)="submitUpsert()">
  <ion-datetime
    display-format="MM DD, YYYY"
    picker-format="MM DD YYYY"
    min="2010"
    max="2030"
    class="form__group__item--input has-value"
    formControlName="date"
    placeholder="Select Date"
    [value]=date
    [(ngModel)]="event.today"
    (ngModelChange)="event.today"
  ></ion-datetime>
</form>

在我的表单控制器中,我有:

constructor(
  private db: DatabaseService,
  private modalController: ModalController,
  private formBuilder: FormBuilder
) {
  this.upsert = this.formBuilder.group({
    title: ['', Validators.compose([Validators.required])],
    date: ['', Validators.compose([Validators.required])],
    notes: [''],
    location: [''],
    timezone: [''],
  });
  this.event.today = moment().toISOString(true);
  this.event.timezone = moment().format('ZZ');
}

最终,我使用表单提交操作

submitUpsert() {
  console.log("new date", this.event.today);
  if(this.upsert.invalid) {
    const error = {
      code: "001",
      message: this.upsert.status
    };
    this.showError(error);
  } else {
    this.db.upsert(this.upsert.value).then(eid => {
      console.log("Success", eid);
      this.hideUpsert();
    }, error => {
      this.showError(error);
      console.error(error);
    });
  }
}

在最新的 beta API 中,没有提到使用 [(ngModel)] 或 (ngModelChange),但这是我可以预先选择默认日期(今天)的唯一方法。

不幸的是,它没有更新模型或表单对象。有什么想法吗?

【问题讨论】:

    标签: ionic-framework datepicker ionic4


    【解决方案1】:

    您同时使用了 ngModel 和 FormControlName。使用任何一个。您可以使用 setValue() 方法更新表单控件的值。

    this.event.today = moment().toISOString(true);
    this.upsert.get('date').setValue(this.event.today);
    

    【讨论】:

      【解决方案2】:

      尝试像这样&lt;ion-datetime [(ngModel)]="newsItem.validTo" name="validTo"&gt;&lt;/ion-datetime&gt; 绑定模型如果ion-datetime 在ngForm 内,则name 属性是必需的。 这在 Ionic 4 中对我有用。

      【讨论】:

        猜你喜欢
        • 2018-05-28
        • 1970-01-01
        • 1970-01-01
        • 2019-12-19
        • 1970-01-01
        • 2020-12-17
        • 1970-01-01
        • 2020-04-21
        • 2020-03-27
        相关资源
        最近更新 更多