3

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.

2
  • A couple things to consider: do you need cross browser compatibility? (There is input[type=date], but it doesn't have support in IE11, Safari, or Firefox currently: caniuse.com/#search=input%20date) And form validation: should your form be invalid if the user enters something non-date (e.g. 'asdf')? Commented Jan 14, 2017 at 16:40
  • yes, exactly. many thanks @stealththeninja. Commented Jan 16, 2017 at 2:55

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@LalitUmbakar thanks you, this helpfull. but how if i want make Validator for the display value?
1

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

1 Comment

This is working fine in CHROME. But, I dont know why this is not working in SAFARI?

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.