7

The [(ngModel)] is not setting default value for date picker. I have tried various different ways to populate the date picker but have been unable to.

My HTML

<input id="START_DATE" type="datetime-local" [(ngModel)]="startDate"/>

In that example the binding works but I am unable to set the default value.

I can set the value if i just interpolate the value but then i lose my 2 way binding. value="{{startDate}}"

3 Answers 3

10

Plunker - https://plnkr.co/edit/s5OMg2olU2yHI246nJOG?p=preview

<input type="date" [ngModel] ="dt | date:'yyyy-MM-dd'" (ngModelChange)="dt = $event">
Sign up to request clarification or add additional context in comments.

1 Comment

this works great but have to ask why it can't just use [(ngModel)] directly with date?
5

You can bind a string type property to the input date type. You have to convert the "Date object" to a "string" and store the string value in a class component property. Bind the respective property (component class) to the HTML element (template).

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  startDate = new Date().toISOString().slice(0, 16);

  constructor(){
  }
}

You can also create a customizable "date to string" format function as per the use-case.

Comments

2

I cannot comments that last answer by my reputation. It is low and I don't know why stackoverflow don't let me upgrade it. That last one works for me and better because I needed only date and I used

startDate = new Date().toISOString().slice(0, 10)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.