3

This is my HTML code:

<div class="form-group">
  <label class="form-control-label" for="field_start">Start</label>
  <input type="datetime-local" class="form-control" name="start" id="field_start" [(ngModel)]="service.startDate" />
</div>

Therefore, startDate is stored as a number (Long) but I want to display a datetime-local. I have really no idea how to do it. I'm using the same component for creating and updating a model. Creating is working cause I can manipulate the value in the called function.

Rohit.007
  • 3,414
  • 2
  • 21
  • 33
1thingtodo
  • 95
  • 2
  • 15
  • *Creating is working cause I can manipulate the the value in the called function*: what does that mean. I guess you mean that you can transform the string to a number before posting the value. If so, just do the reverse when displaying the form: transform the number to a string and bind that string to the form. – JB Nizet Aug 10 '18 at 16:23
  • You can call a function every time the ngModel changes `(ngModelChange)="myFunction($event)"` – Ploppy Aug 10 '18 at 16:24
  • @JBNizet when the form is submitted I call a function. In the function I can convert the datetime-local string to a number and store it. When I want to update the Object I pull the database status and the input field displays the number instead of the formatted datetime-local. – 1thingtodo Aug 10 '18 at 16:29
  • So, do what I just said in my comment: get the data from the server, and then transform the number you get into a datetime-local string. – JB Nizet Aug 10 '18 at 16:34
  • @JBNizet I know what you mean but therefore I had to change my typescript code from number to any. You think it's ok to do so? I'm an Angular newbie – 1thingtodo Aug 10 '18 at 16:43
  • No. You need to have a type to represent what your form displays (containing strings), and a differet type to represent what you receive and/or send as JSON (containing numbers). They are not the same thing. – JB Nizet Aug 10 '18 at 16:45
  • The problem is that my database stores a Long. I have to display/store a DateTime-local. Angular/TS has no Datetime-local type. – 1thingtodo Aug 10 '18 at 16:47

2 Answers2

3

You can change 2-way binding [(ngModel)] to separate property and event bindings using [ngModel] and (ngModelChange). Then you can use a pipe to format input value.

Using Pipes within ngModel on INPUT Elements in Angular

Shivam Sinha
  • 133
  • 6
0

You can try angular-moment library which supports converting datetime to local to your timezone.

var a = moment.utc([2011, 0, 1, 8]);
a.local();
Suresh Kumar Ariya
  • 9,516
  • 1
  • 18
  • 27