angular - 使用响应式表单时禁用(设为只读)mat-datepicker 上的文本输入

标签 angular angular-material2 angular-reactive-forms

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

detailed instructions in the Angular Material 2 docs关于如何禁用 mat-datepicker 的不同部分但是,这些似乎并未涵盖如何在响应式表单的一部分时禁用文本输入。

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 收到以下消息:

It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true when you set up this control in your component class, the disabled attribute will actually be set in the DOM for you. We recommend using this approach to avoid 'changed after checked' errors. Example: form = new FormGroup({ first: new FormControl({value: 'Nancy', disabled: true})});

我更新了 FormGroup在组件中禁用 FormControl ,这具有禁用输入的预期效果,但是,如果您随后获得 FormGroup 的值使用 this.form.value禁用的表单控件不再存在。

是否有解决此问题的方法,它不涉及使用 ngModel 的单独模板驱动表单只是为了 mat-datepicker(s)?

编辑: 在帖子标题中添加“只读”以澄清这与禁用控件无关 - 因为我要问的是将输入元素设置为只读,但不是无法控制自己

最佳答案

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

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

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

关于angular - 使用响应式表单时禁用(设为只读)mat-datepicker 上的文本输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47341535/

相关文章:

angular - Angular Material 2 中的 md 表

angular - 是否可以使 Angular ReactiveForm ValidatorFn 设置错误几秒钟?

javascript - 类型 'File' 的参数不可分配给类型 'string' 的参数

javascript - Angular2 - sass 无法在 angular-cli 上构建

css - Angular2 Material md-select 不与 md-input 内联

angular - 升级到 Angular 6/Material 6 后,为什么我会遇到 'mat-input-container is not a known element'?

Angular 2 自定义验证器检查何时需要两个字段之一

javascript - 检查单选按钮是否脏/以 react 形式被触摸

angular - 将项目从 SystemJS 移动到 Angular CLI/Webpack

javascript - Angular2 CLI 中出现意外标记 <