首页 文章

如何将model.property绑定到angular-2-material日期选择器的ngModel?

提问于
浏览
0

To begin :我正在尝试使用angular-2材质组件创建表单 . 我有一个包含日期选择器的表单:

<md-form-field>
          <input readonly="true" mdInput [mdDatepicker]="regDatePicker" placeholder="{{'client.regdate-placeholder'}}">
          <md-datepicker-toggle mdSuffix [for]="regDatePicker"></md-datepicker-toggle>
          <md-datepicker #regDatePicker  startView="month" [startAt]="currentDate"></md-datepicker>
        </md-form-field>

打字稿:

public client: IPerson;
    @ViewChild("regDatePicker")
    public regDatePicker: MdDatepicker<Date>;

Whats is needed :要么将日期选择器的ngModel绑定到client.registrationDate,要么从后面的代码设置regDatePicker的值 .

What i get: :在[(值)]绑定的情况下,我看到错误

Can't bind to 'mdDatepicker' since it isn't a known property of 'input'

试图在代码后面设置它,但找不到适当的属性名称或字段来设置值 .

Question :为了绑定模型中的数据,我该怎么办?

UPD: 添加了引用输入的代码

@ViewChild("dpDateInput")
public dpDate: MdDatepickerInput<Date>;

public ngAfterViewInit(): void {
   console.log(`---------->>>>>>>>> before ${ this.dpDate.value}`)
   this.dpDate.value = this.client.regDate;
   console.log(`---------->>>>>>>>> after ${ this.dpDate.value}`);
}

1 回答

  • 0

    在引用 value 时尝试使用 mdDatepickerInput 而不是 mdDatepicker .

    EDIT

    反映UI更改的一种方法是将 ChangeDetectorRef 注入组件的构造函数并调用其 detectChanges() 方法 .

    import { ChangeDetectorRef } from '@angular/core';
    
    constructor (private ref: ChangeDetectorRef) {}
    
    public ngAfterViewInit(): void {
       console.log(`---------->>>>>>>>> before ${ this.dpDate.value}`)
       this.dpDate.value = this.client.regDate;
       this.ref.detectChanges();
       console.log(`---------->>>>>>>>> after ${ this.dpDate.value}`);
    }
    

相关问题