Angular 2 - 使用带有mdDatepicker输入的md-hint

时间:2017-06-21 14:51:17

标签: angular angular2-forms

我是[Mango]的新用户,我正在使用Angular 2加上md-hint

我可以使用mdDatepicker和'输入'。

不起作用的HTML

md-select

可行的HTML(仅输入字段)

<md-input-container>
    <input mdInput placeholder="Start date" name="startDatepicker" required ngModel #startDatepicker="ngModel">
    <button mdSuffix [mdDatepickerToggle]="startDatepicker"></button>
    <md-hint *ngIf="startDatepicker.errors && (startDatepicker.dirty || startDatepicker.touched)" [hidden]="!startDatepicker.errors.required">
        Start date is required.
    </md-hint>                    
</md-input-container>

所有我使用的代码都在<md-input-container> <input mdInput placeholder="Start date" name="startDatepicker" required ngModel #startDatepicker="ngModel"> <md-hint *ngIf="startDatepicker.errors && (startDatepicker.dirty || startDatepicker.touched)" [hidden]="!startDatepicker.errors.required"> Start date is required. </md-hint> </md-input-container> 上,删除了input

1 个答案:

答案 0 :(得分:2)

实际上,您发布的两个代码都会引发一些错误。为什么呢?

1 - 您在[mdDatepicker]="yourRefToDatePicker";

中遗漏了input

2 - [mdDatepickerToggle]应该指向一个datepicker实例(而不是你正在做的ngModel):

[mdDatepickerToggle]="yourRefToDatePicker"

3 - 你应该有一个md-datepicker的实例:

<md-datepicker #yourRefToDatePicker></md-datepicker>

以下是使用md-datepicker

的工作示例
<md-input-container>
  <input mdInput
         placeholder="Start date"
         name="startDatepicker"
         required
         ngModel
         [mdDatepicker]="picker"
         #startDatepicker="ngModel">
  <button type="button" mdSuffix [mdDatepickerToggle]="picker"></button>
  <md-hint *ngIf="startDatepicker.errors && (startDatepicker.dirty || startDatepicker.touched)" [hidden]="!startDatepicker.errors.required">
    Start date is required.
  </md-hint>
</md-input-container>
<md-datepicker #picker></md-datepicker>

那说,这里有一些注意事项:

1 - 在同一元素上使用*ngIf[hidden]没有意义(您也应该更喜欢*ngIf)。

如果您只想检查required 错误,可以执行此操作(使用下面的md-error作为第2条声明):

<md-hint *ngIf="startDatepicker.errors?.required && (startDatepicker.dirty || startDatepicker.touched)">
  Start date is required.
</md-hint>

2 - 建议使用 Material2 显示错误,以使用md-error 指令,如下所示:

<md-error *ngIf="condition">
  <!-- your error message -->
</md-error>

最终的代码可能是这样的:

<md-input-container>
  <input mdInput
       placeholder="Start date"
       name="startDatepicker"
       required
       ngModel
       [mdDatepicker]="picker"
       #startDatepicker="ngModel">
  <button type="button" mdSuffix [mdDatepickerToggle]="picker"></button>
</md-input-container>

<ng-container *ngIf="startDatepicker.invalid && (startDatepicker.dirty || startDatepicker.touched)">
  <md-error *ngIf="startDatepicker.hasError('required')">
    Start date is required.
  </md-error>
  <md-error *ngIf="startDatepicker.getError('mdDatepickerMax') as datepickerMaxError">
    Start date should be less than {{ datepickerMaxError.max }}
  </md-error>
  <!-- another error(s) -->
</ng-container>

<md-datepicker #picker></md-datepicker>

PLUNKER