gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:57:44 24 4
gpt4 key购买 nike

我正在使用 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 formdirective. If you set disabled to true when you set up this control inyour component class, the disabled attribute will actually be set inthe DOM for you. We recommend using this approach to avoid 'changedafter 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com