'Angular setting default value of HTML datepicker
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}}"
Solution 1:[1]
Plunker - https://plnkr.co/edit/s5OMg2olU2yHI246nJOG?p=preview
<input type="date" [ngModel] ="dt | date:'yyyy-MM-dd'" (ngModelChange)="dt = $event">
Solution 2:[2]
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.
Solution 3:[3]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Younis Ar M |
| Solution 2 | gagan |
| Solution 3 | Pedro Suárez |
