ntgCleaner
ntgCleaner

Reputation: 5985

Ionic 4 datetime picker does not update its variable

I am using the ionic 4 ion-datetime picker to try to select a date in a form, though when a new date is selected, it does not update the variable.

I've tried using all of the different combinations I know, but I've included all of them here in this example.

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

and in my form controller I have:

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

And eventually, I use the form submit action

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

In the latest beta API, it does not mention to use [(ngModel)] or (ngModelChange), but it was the only way I could get a default date (of today) pre-selected.

Unfortunately, it's not updating the model nor the form object. Any thoughts?

Upvotes: 1

Views: 2898

Answers (2)

Patronaut
Patronaut

Reputation: 1370

Try bind the model like this <ion-datetime [(ngModel)]="newsItem.validTo" name="validTo"></ion-datetime> The name attribute is required if the ion-datetime is within an ngForm. This worked for me in Ionic 4.

Upvotes: 0

Suresh Kumar Ariya
Suresh Kumar Ariya

Reputation: 9784

You are using both ngModel and FormControlName. Use either one. you can update the form control value using setValue() method.

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

Upvotes: 2

Related Questions