Fabian Fabian - 2 months ago 28
Dart Question

Angular2 dart DateTime not type save?

I have an Angular2 Dart application where I have the following type defined.

class Event {
final int id;
DateTime startDate;
}


I now want to let the user input a new date so I bind this field the following.

<div class="form-group">
<label for="start_date">Start Date</label>
<input type="text" class="form-control" required
[(ngModel)]="event.startDate"
ngControl="start_date"
#start_date="ngForm">
<div [hidden]="start_date.valid" class="alert alert-danger">
Start date is required
</div>
</div>


Now I am surprised to see that the user can input an invalid date string and that if I e.g. do a print(event.startDate) I get this invalid string. My impression was that the DateTime variable would be type safe but it just seems to behave like an ordinary string. What am I missing. I understand that I would need to add validators but why do I have a type defined in the first place? I would at least expect it to blow up :-)

So how would you go about entering dates correctly? If I change the input type to "date" then it can't even load the inital value due to the time part of the DateTime.

Answer

So I now took G√ľnters advice and solved this with the following construct:

class Event {
  final int id;
  DateTime startDate;

  String get startDateStr {
    var formatter = new DateFormat('yyyy-MM-dd');
    return formatter.format(startDate);
  }

  void set startDateStr(String date) {
    startDate = DateTime.parse(date);
  }
}

With this extra properties it is now possible to write the following in the html template:

<div class="form-group">
  <label for="start_date">Start Date</label>
  <input type="date" class="form-control" required
         [(ngModel)]="event.startDateStr"
         ngControl="start_date"
         #start_date="ngForm">
  <div [hidden]="start_date.valid" class="alert alert-danger">
    Start date is required
  </div>
</div>

This looks to me the cleanest and preserves the Event class structure. I still would be interested if there is a common pattern for something like this, if yes please comment on my answer.

Comments