[html] Angular 2 Date Input not binding to date value

trying to get a form set up but for some reason, the Date input in my html is not binding to the object's date value, despite using [(ngModel)]

html:

<input type='date' #myDate [(ngModel)]='demoUser.date'/><br>

form component:

export class FormComponent {
    demoUser = new User(0, '', '', '', '', new Date(), '', 0, [], []);  
}

User class:

export class User {
    constructor (
        public id: number,
        public email: string,
        public password: string,
        public firstName: string,
        public lastName: string,
        public date: Date,
        public gender: string,
        public weight: number,
        public dietRestrictions: string[],
        public fitnessGoals: string[]
    ){

    }
}

A test output reveals the current "new" Date as the object's value, but the input doesn't update the User object's date value or reflect the value, suggesting neither of the two-way bindings are working. Help would be greatly appreciated.

This question is related to html angular typescript angular2-forms

The answer is


If you are using a modern browser there's a simple solution.

First, attach a template variable to the input.

<input type="date" #date />

Then pass the variable into your receiving method.

<button (click)="submit(date)"></button>

In your controller just accept the parameter as type HTMLInputElement and use the method valueAsDate on the HTMLInputElement.

submit(date: HTMLInputElement){
    console.log(date.valueAsDate);
}

You can then manipulate the date anyway you would a normal date.

You can also set the value of your <input [value]= "..."> as you would normally.

Personally, as someone trying to stay true to the unidirectional data flow, i try to stay away from two way data binding in my components.


In Typescript - app.component.ts file

export class AppComponent implements OnInit {
    currentDate = new Date();
}

In HTML Input field

<input id="form21_1" type="text" tabindex="28" title="DATE" [ngModel]="currentDate | date:'MM/dd/yyyy'" />

It will display the current date inside the input field.


In .ts :

today: Date;

constructor() {  

    this.today =new Date();
}

.html:

<input type="date"  
       [ngModel]="today | date:'yyyy-MM-dd'"  
       (ngModelChange)="today = $event"    
       name="dt" 
       class="form-control form-control-rounded" #searchDate 
>

Angular 2 completely ignores type=date. If you change type to text you'll see that your input has two-way binding.

<input type='text' #myDate [(ngModel)]='demoUser.date'/><br>

Here is pretty bad advise with better one to follow:

My project originally used jQuery. So, I'm using jQuery datepicker for now, hoping that angular team will fix the original issue. Also it's a better replacement because it has cross-browser support. FYI, input=date doesn't work in Firefox.

Good advise: There are few pretty good Angular2 datepickers:


Instead of [(ngModel)] you can use:

// view
<input type="date" #myDate [value]="demoUser.date | date:'yyyy-MM-dd'" (input)="demoUser.date=parseDate($event.target.value)" />

// controller
parseDate(dateString: string): Date {
    if (dateString) {
        return new Date(dateString);
    }
    return null;
}

You can also choose not to use parseDate function. In this case the date will be saved as string format like "2016-10-06" instead of Date type (I haven't tried whether this has negative consequences when manipulating the data or saving to database for example).


As per HTML5, you can use input type="datetime-local" instead of input type="date".

It will allow the [(ngModel)] directive to read and write value from input control.

Note: If the date string contains 'Z' then to implement above solution, you need to trim the 'Z' character from date.

For more details, please go through this link on mozilla docs.


use DatePipe

> // ts file

import { DatePipe } from '@angular/common';

@Component({
....
providers:[DatePipe]
})

export class FormComponent {

constructor(private datePipe : DatePipe){}

    demoUser = new User(0, '', '', '', '', this.datePipe.transform(new Date(), 'yyyy-MM-dd'), '', 0, [], []);  
}

Angular 2 , 4 and 5 :

the simplest way : plunker

<input type="date" [ngModel] ="dt | date:'yyyy-MM-dd'" (ngModelChange)="dt = $event">

you can use a workaround, like this:

<input type='date' (keyup)="0" #myDate [(ngModel)]='demoUser.date'/><br>

on your component :

 @Input public date: Date,

In your component

let today: string;

ngOnInit() {
  this.today = new Date().toISOString().split('T')[0];
}

and in your html file

<input name="date" [(ngModel)]="today" type="date" required>

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to typescript

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type?

Examples related to angular2-forms

How can I manually set an Angular form field as invalid? Angular 2 Cannot find control with unspecified name attribute on formArrays Remove all items from a FormArray in Angular Angular ReactiveForms: Producing an array of checkbox values? How to make readonly all inputs in some div in Angular2? tslint / codelyzer / ng lint error: "for (... in ...) statements must be filtered with an if statement" Min / Max Validator in Angular 2 Final TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm" Can't bind to 'formGroup' since it isn't a known property of 'form' ngModel cannot be used to register form controls with a parent formGroup directive