【问题标题】:Angular 2 material datepicker ngModel not displaying valueAngular 2材料日期选择器ngModel不显示值
【发布时间】:2018-08-05 06:05:12
【问题描述】:

我是角度和材料 2 的新手,我在表单中使用材料日期选择器来显示和选择日期。我可以选择日期并绑定到 ngModel。但是当我尝试将我的响应绑定到 ngModel 时,什么也没显示。我已将字符串日期转换为日期,然后绑定到 ngModel。以下是代码,请帮助我在哪里丢失。

 <mat-form-field>
  <input matInput id="dateOfBirth" name="dateOfBirth" [matDatepicker]="dateOfBirth" 
          class="form-control" [(ngModel)]="customer.dateOfBirth"
            placeholder="Date of birth" required>
 <mat-datepicker-toggle matSuffix [for]="dateOfBirth"></mat-datepicker-toggle>
          <mat-datepicker #dateOfBirth></mat-datepicker>
          <mat-error>Date of birth is required</mat-error>
        </mat-form-field>

我的 ts 文件从 json 获取响应

   customer: CustomerModel = new CustomerModel();
 this.customerService.getResponse().subscribe(resp => {
           this.customer= resp;
 console.log('Date:'+this.customer.dateOfBirth);// able to print
        });

    Class CustomerModel {
        dateOfBirth: Date; 
         //other customer details
      }

我在这里创建了示例https://stackblitz.com/edit/angular-pvqugs

【问题讨论】:

  • 您是否在控制台中看到错误消息?
  • 你能尝试在 stackblitz 上提供你的代码吗?
  • @ConnorsFan:不,我没有看到任何错误

标签: angular angular-material2


【解决方案1】:

我解决了,我正在转换字符串日期格式,然后尝试与 ngModel 绑定。我删除了格式日期部分(使用 DatePipe)并将字符串转换为日期。

    if (date) {
  let dateOld: Date = new Date(date);
  return dateOld;
    }

这里是更新的代码 https://stackblitz.com/edit/angular-pvqugs

【讨论】:

    【解决方案2】:

    在您的 stackblitz 示例中,在初始化时,您将日期设置为字符串值,日期选择器组件不接受该值。如果您注释 ngOnInit 方法,它将显示该值。

    此处的代码中没有足够的详细信息来了解 customer.dateOfBirth 是什么类型。它适用于日期类型。

    文档中的此示例显示了绑定组件的不同方式,即使使用序列化值:https://stackblitz.com/angular/dlerqrdamjl?file=app%2Fdatepicker-value-example.html

    【讨论】:

    • 我的 json 响应正在发送字符串日期,我已将字符串转换为日期,但仍然无法正常工作
    猜你喜欢
    • 2018-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多