Tadija Bagarić
Tadija Bagarić

Reputation: 2701

Update <ion-datetime> control data using formGroup

I have a form that is built using 'FormBuilder' and it contains a date control . How can I set (update) data to that control using patchValue()?

The control has displayFormat="DD.MM.YYYY" set in the template.

Data on all other controls ( and ) is set , but the date control remains empty.

page/component/.ts file

userDataForm: FormGroup;
user: UserModel;

constructor(
    private formBuilder: FormBuilder
) {
    this.userDataForm = this.buildForm();
}

buildForm(){
    return this.formBuilder.group({
        firstName: ['', Validators.compose([
          Validators.required
        ])],
        dateOfBirth: ['', Validators.compose([
          Validators.required
        ])]
    });
}

ionViewWillEnter() {
    // load data...
    refreshForm();
}

refreshForm(){
    this.userDataForm.patchValue({
        firstName: this.user.firstName,
        dateOfBirth: new Date("2016-04-19T18:03:40.887"), // does not work
    });
}

Template:

<ion-content padding>
    <ion-list>
        <form [formGroup]="userDataForm">

            <ion-item>
                <ion-label floating>Name: *</ion-label>
                <ion-input formControlName="firstName" type="text"></ion-input>
            </ion-item>

            <ion-item>
                <ion-label floating>Date: *</ion-label>
                <ion-datetime formControlName="dateOfBirth" displayFormat="DD.MM.YYYY"></ion-datetime>
            </ion-item>

        </form>
    </ion-list>
</ion-content>

Upvotes: 0

Views: 7751

Answers (1)

Tadija Bagarić
Tadija Bagarić

Reputation: 2701

Thanks to Eliseo in the comments for leading me to the answer.

<ion-datetime> expects a date string, and not a date object so this works:

refreshForm(){
    this.userDataForm.patchValue({
        firstName: this.user.firstName,
        dateOfBirth: (new Date("2016-04-19T18:03:40.887")).toJSON(), 
    });
}

in my case user.dateOfBirth is of type date so I use it like this:

refreshForm(){
    this.userDataForm.patchValue({
        firstName: this.user.firstName,
        dateOfBirth: this.user.dateOfBirth.toJSON(), 
    });
}

Upvotes: 6

Related Questions