使用被动表单时,禁用mat-datepicker上的文本输入

时间:2017-11-17 00:44:53

标签: angular angular-material2 angular-reactive-forms

我正在使用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   您的组件类,实际上将设置disabled属性   你的DOM。我们建议使用此方法来避免更改   检查后#39;错误。   例:         form = new FormGroup({first:new FormControl({value:&#39; Nancy&#39;,disabled:true})});

我更新了组件中的FormGroup以禁用FormControl,这具有禁用输入所需的效果,但是,如果您随后使用{获取FormGroup的值{1}}禁用的表单控件不再存在。

是否有解决方法,不涉及使用this.form.value仅用于mat-datepicker的单独的模板驱动表单?

3 个答案:

答案 0 :(得分:32)

创建一个禁用的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

答案 1 :(得分:1)

要扩展developer033的答案,动态切换readonly的{​​{1}}状态,请使用组件变量修改input属性。

动态切换为只读

请参见 Stackblitz Demo

app.component.html

readonly

app.component.ts

<input matInput 
  [readonly]="inputReadonly"   <!-- Update `readonly` property using variable -->
  [matDatepicker]="dateJoined" 
  placeholder="Date joined" 
  formControlName="dateJoined">

答案 2 :(得分:1)

这有助于我们禁用输入:

<mat-form-field appearance="fill">
    <mat-label>Input disabled</mat-label>
    <input matInput [matDatepicker]="dp3" disabled>
    <mat-datepicker-toggle matSuffix [for]="dp3"></mat-datepicker-toggle>
    <mat-datepicker #dp3 disabled="false"></mat-datepicker>
</mat-form-field>

Ref

相关问题