angular - 从反应形式驱动材料日期选择器控制
问题描述
我有日期选择器,它应该通过复选框切换单击动态禁用和启用。库角材料 6 中的所有组件。由于我对表单处理程序使用了反应式方法,因此我不能简单地使用[disable]
指令。我得到了进一步的错误:
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}, Validators.required),
last: new FormControl('Drew', Validators.required)
});
我有想法直接在 TS 中替换FormContol
内部,如下所示:FormGroup
toggleDatePicker() {
this.isDateRange = !this.isDateRange;
this.form.removeControl('to');
if (this.isDateRange) {
this.form.addControl('to', new FormControl({value: new Date(), disabled: false}))
} else {
this.form.addControl('to', new FormControl({value: null, disabled: true}))
}
}
这适用于input
标签,但mat-datepicker-toggle
仍保持初始状态。mat-datepicker-toggle
状态不依赖于FormControl
.
<mat-form-field>
<input
matInput
[matDatepicker]="to"
formControlName="to"
[disabled]="isDateRange"
>
<mat-datepicker-toggle matSuffix [for]="to"></mat-datepicker-toggle> // THIS IS NO CHANGE(
<mat-datepicker #to></mat-datepicker>
</mat-form-field>
独立于我的FormControl
操作mat-datepicker-toggle
,始终处于相同的状态:
我怎样才能操纵mat-datepicker-toggle
思想FromControl
?
解决方案
您需要使用控件上的一些方法来以编程方式切换控件禁用disable()
状态。enable()
请查看此 stackblitz 示例
https://stackblitz.com/edit/angular-lenyzk?embed=1&file=app/datepicker-overview-example.ts
HTML 模板
<form [formGroup]="form">
<mat-checkbox (click)="toggleCtrState()">Toggle Control State</mat-checkbox>
<mat-form-field>
<input
matInput
[matDatepicker]="to"
formControlName="to"
>
<mat-datepicker-toggle matSuffix [for]="to"></mat-datepicker-toggle>
<mat-datepicker #to></mat-datepicker>
</mat-form-field>
</form>
零件
import { Component } from '@angular/core';
import { FormControl, FormGroup, FormBuilder, Validators } from '@angular/forms';
/** @title Basic datepicker */
@Component({
selector: 'datepicker-overview-example',
templateUrl: 'datepicker-overview-example.html',
styleUrls: ['datepicker-overview-example.css'],
})
export class DatepickerOverviewExample {
form = new FormGroup({
to: new FormControl('', Validators.required),
});
toggleCtrState() {
const ctrl = this.form.get('to');
if (ctrl.disabled) {
ctrl.enable();
} else {
ctrl.disable();
}
}
}
推荐阅读
- angular - 无法获得 Textarea 的高度
- azure-active-directory - 为多个应用程序/环境配置 adal.js
- ruby - selenium/webdriver/firefox/binary.rb:134:in `path': 无法修改冻结字符串 (FrozenError)
- vue.js - Vue Slider Component - 同时启用拖尾和点击更新
- c# - 在 dotnet-core 控制台应用程序和常规 winforms 应用程序之间进行通信的最佳方式
- java - 我如何使用 compareTo 来迭代用户输入
- node.js - 错误:EPERM:不允许操作,运行 npm publish 时取消链接
- python - 项目的 .py 文件位于 virtualenvwrapper 中的什么位置?
- python - Tensorflow:根据输入创建向量
- java - PriorityQueue 的顺序不对