【问题标题】:Angular2 dart DateTime not type save?Angular2 dart DateTime 不输入保存?
【发布时间】:2016-09-15 19:34:01
【问题描述】:

我有一个 Angular2 Dart 应用程序,其中定义了以下类型。

class Event {
  final int id;
  DateTime startDate;
}

我现在想让用户输入一个新日期,所以我将此字段绑定到以下内容。

<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>

现在我很惊讶地看到用户可以输入一个无效的日期字符串,如果我例如做一个 print(event.startDate) 我得到这个无效的字符串。我的印象是 DateTime 变量是类型安全的,但它看起来就像一个普通的字符串。我错过了什么。我知道我需要添加验证器,但为什么我首先定义了一个类型?我至少希望它会爆炸:-)

那么您将如何正确输入日期?如果我将输入类型更改为“日期”,那么由于 DateTime 的时间部分,它甚至无法加载初始值。

【问题讨论】:

    标签: angular dart


    【解决方案1】:

    所以我现在采纳了 Günters 的建议并通过以下结构解决了这个问题:

    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);
      }
    }
    

    有了这个额外的属性,现在可以在 html 模板中编写以下内容:

    <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>
    

    这在我看来是最干净的,并且保留了 Event 类结构。如果有这样的共同模式,我仍然会感兴趣,如果是,请评论我的答案。

    【讨论】:

      【解决方案2】:

      在生产模式下没有类型信息。它们仅在选中(开发模式)下可用。

      不清楚你使用的是什么模式。

      输入元素值是一个字符串,您需要注意以DateTime 格式 (DateTime.parse()) 获取它。 仅仅因为您使用的变量是 DateTime 类型,并不意味着您“扔”给它的任何东西都会自动成为有效日期。

      【讨论】:

      • 嗯,我正在使用 pub serve 和 Dartium,所以我认为这将是一个开发设置。
      • 我刚刚提到了这一点,所以您知道存在差异。无论您使用哪种模式,我的答案的其他部分都适用。根据模式,您可能会遇到不同的错误。
      • 谢谢,我现在知道并且完全理解这一点。我只是想知道为什么我的错误消失了,但这可以通过生产模式来解释。我仍然不知道如何绑定 DateTime。我例如尝试: [ngModel]="event.startDate | date: 'y-M-d'" 设置初始值,但最终显示为 'tt.mm.jjjj'
      • ngModel 使用 value´ property. Check https://dartpad.dartlang.org/191ca4b46d0ea30cafa67e536e46f141. Select a date and click the button, then check the console output (link on the top right). What you can do is bind to a getter/setter that converts between String` 和 DateTime 或使用 ControlValueAccessor 包装 &lt;input type="datetime"&gt; 构建自定义 MyDateTimeComponent 组件以便于重用(这仍然需要您实现String 和 DateTime 之间的转换。
      猜你喜欢
      • 1970-01-01
      • 2017-06-23
      • 1970-01-01
      • 2013-07-24
      • 1970-01-01
      • 1970-01-01
      • 2013-08-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多