首页 文章

使用反应形式时,禁用mat-datepicker上的文本输入

提问于
浏览 280 次
8

我正在使用Angular Material 2的 mat-datepicker 并希望禁用输入元素,因此用户无法使用文本输入编辑值 .

关于如何禁用 mat-datepicker 的不同部分有detailed instructions in the Angular Material 2 docs但是,这些似乎没有涵盖当它是被动形式的一部分时如何禁用文本输入 .

Angular Material文档建议您通过以下方式禁用文本输入:

<mat-form-field>
              // Add the disabled attribute to the input element ======
              <input disabled                          
                     matInput 
                     [matDatepicker]="dateJoined" 
                     placeholder="Date joined" 
                     formControlName="dateJoined">
              <mat-datepicker-toggle matSuffix [for]="dateJoined"></mat-datepicker-toggle>

              // Add [disabled]=false to the mat-datepicker =======
              <mat-datepicker [disabled]="false" 
                              startView="year"  
                              #dateJoined></mat-datepicker>
            </mat-form-field>

但是,如果您的日期选择器是被动表单的一部分,则文本元素保持活动状态,您将从Angular获得以下消息:

看起来您正在使用带有反应式表单指令的disabled属性 . 如果在组件类中设置此控件时将disabled设置为true,则实际将在DOM中为您设置disabled属性 . 我们建议使用此方法来避免“检查后更改”错误 . 示例:form = new FormGroup({first:new FormControl({value:'Nancy',disabled:true})});

我更新了组件中的 FormGroup 以禁用 FormControl ,这具有禁用输入所需的效果,但是,如果您使用 this.form.value 获取 FormGroup 的值,则禁用的表单控件不再存在 .

Is there a work around for this which does not involve having a separate template driven form using ngModel just for the mat-datepicker(s)?

1 回答

  • 16

    要创建一个禁用的 FormControl 非常简单 .

    1 - 不要在模板中使用disabled属性;

    2 - 像这样实例化您的 FormGroup

    this.formGroup = this.formBuilder.group({
      dateJoined: { disabled: true, value: '' }
      // ...
    });
    

    话虽这么说,虽然你想阻止用户在输入中输入内容,你仍然希望让他们通过点击按钮(更具体地说是 matSuffix )来选择日期,对吧?

    如果正确, disable 不会禁用所有输入(包括 matSuffix 中的按钮) .

    要解决您的情况,您可以使用 readonly . 正常实例化 FormGroup 然后在模板中:

    <input                          
      matInput 
      readonly <- HERE
      [matDatepicker]="dateJoined" 
      placeholder="Date joined" 
      formControlName="dateJoined">
    

    DEMO

相关问题