我是新的角度和材料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
}发布于 2018-02-27 20:02:59
我解决了这个问题,我正在转换字符串日期格式,然后尝试绑定到ngModel。我删除了我的格式日期部分(使用DatePipe)和转换字符串到日期。
if (date) {
let dateOld: Date = new Date(date);
return dateOld;
}发布于 2018-02-26 11:43:15
在stackblitz的示例中,在init上,将日期设置为字符串值,而datepicker组件不接受该值。如果您注释ngOnInit方法,它将显示该值。
这里的代码中没有足够的细节来知道什么类型是customer.dateOfBirth。它可以很好地与类型日期。
文档中的这个示例展示了绑定组件的不同方法,即使使用序列化的值:https://stackblitz.com/angular/dlerqrdamjl?file=app%2Fdatepicker-value-example.html。
https://stackoverflow.com/questions/48977393
复制相似问题