Youngz ie
Youngz ie

Reputation: 679

How do I use a date input with ngModel?

I have date input box like this

<input [(ngModel)]="value"
       type="text"
class="form-control">

How do I display and submit the value?

User input should be formatted as dd/MM/yyyy and submit value should be formatted as yyyy/MM/dd.

Upvotes: 3

Views: 4367

Answers (2)

Lalit Umbarkar
Lalit Umbarkar

Reputation: 443

In your template, add a keyup event listener to one input field and set name to another while keeping second hidden.

<input type="text" (keyup)="changeFormat($event)" [(ngModel)]="value" placeholder="Enter a Date here">
<input type="hidden" name="dateField" [attr.value]="returnValue"><hr>
<h1 [hidden]="!value">Hello {{returnValue}}!</h1>

In component create the method to modify the format of date from input field and set it to another variable returnValue which will store formatted date, as shown below.

value: string = '';
returnValue : string = "";

changeFormat($event):void {
  let argDateArr = this.value.split("/");
  let year = argDateArr[2];
  argDateArr[2] = argDateArr[0];
  argDateArr[0] = year;
  this.returnValue = argDateArr.join("/");
}

Plunker can be found here

Hope this helps.

Upvotes: 1

Aravind
Aravind

Reputation: 41543

First

npm install ng2-datepicker --save

You should be using input type date as below

 <input id="textinput" [(ngModel)]="startDate" name="textinput" type="date" placeholder="Start Date" class="form-control input-md">

Ensure that in your package.json has

"ng2-datepicker": "^1.4.7" in it dependencies

Your output will be as enter image description here

Upvotes: 1

Related Questions