1

I use the simple datepicker from angular 2 as follows;

<div class="form-group row">
    <label for="hourdate-field" class="col-md-4  col-form-label text-md-right">Date</label>
    <div class="col-md-7 ">
        <input type="date" formControlName="hourdate" class="form-control">
    </div>
</div>

The datepicker works fine after selecting and saving a date, although when selecting an existing object to edit, the placeholder mm/dd/yyyy is shown instead of the object date.

Any ideas on how to show the date value of an object instead of the placeholder?

Per request below form init;

initForm() {
    let hour_id = 0; 
    let customer_id = 0;
    let payer_id = 0;
    let project = '';
    let description = '';
    let hours = '';
    let hourdate = new Date('01-01-1900');

    if (this.selected === true) { //edit existing
        hour_id = this.selectedHour.hour_id;
        customer_id = this.selectedHour.customer_id;
        payer_id = this.selectedHour.payer_id;
        project = this.selectedHour.project;
        description = this.selectedHour.description;
        hours = this.selectedHour.hours;
        hourdate = this.selectedHour.hourdate;   
    }

    //create the form
    this.hourForm = this.formBuilder.group({
        hour_id:[hour_id],
        customer_id: [customer_id],
        payer_id: [payer_id],
        project: [project],
        description: [description],
        hours: [hours],
        hourdate: [hourdate]
    });
}

Using string instead of date pointed me in the right direction

Changes:

let hourdate = '1900-01-01'; 
hourdate = this.datepipe.transform(this.selectedHour.hourdate, 'yyyy-MM-dd'); 
phicon
  • 3,549
  • 5
  • 32
  • 62

2 Answers2

1

To initialise the date you should pass it in the proper format (string, not date object), see https://stackoverflow.com/a/14212715/1990451.

In order to fix your issue, just change the hourdate assignment to the following:

let hourdate = '1900-01-01';
Community
  • 1
  • 1
smnbbrv
  • 23,502
  • 9
  • 78
  • 109
1

The form control's value is just a text string formatted YYYY-MM-dd and not an actual date. So, we can initialize correctly by doing the following:

initForm() {
    <...>
    let hourdate = '1900-01-01';

    //create the form
    this.hourForm = this.formBuilder.group({
        <...>
        hourdate: [hourdate]
    });
}

If there's a model that needs binding we can subscribe to the valueChanges property which takes the form of:

this.hourForm.controls['hourdate'].valueChanges.subscribe(value => [myModelProperty] = new Date(value));

Plunker

silentsod
  • 8,165
  • 42
  • 40