我有一个反应式。在编辑时,我想禁用一个控件。
以下是工作原理:
this.myForm.controls['analysis_horizon'].disable();
但是,密钥analysis_horizon不再在我的myForm.value散列中。
如何禁用具有反应式表单的字段,但保持表单值的哈希值?
我尝试过disabled=,但得到的结果如下:
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)
});
我在编辑时将数据从我的数据库加载到表单控件中,但我需要一个字段不允许更改。
发布于 2017-04-06 11:27:20
您可以使用getRawValue()而不是value属性。根据documentation的说法
FormGroup的聚合值,包括任何禁用的控件。
如果您希望包含所有值,而不考虑禁用状态,请使用此方法。否则,value属性是获取组的值的最佳方法。
this.myForm.getRawValue()
发布于 2018-06-12 13:54:25
我的解决方案是使用attr.disabled
<select formControlName="foo"
[attr.disabled]="disabled == true ? true : null">
</select>
假设您的组件中有一个disabled属性。您必须返回null not false以启用输入。
发布于 2017-12-20 18:57:07
如果你不想使用getRawValue,这是另一个选择,它改变了从表单中获取值的正常方式。更多我更喜欢只读的原因:https://stackoverflow.com/a/7730719/1678151。
我的解决方案还展示了如何填充表单控件。
component.ts
fillForm(data: any){
if (data != null && data.firstName){
this.form.patchValue({
firstName: data.firstName
})
this.firstNameIsReadOnly = true;
}
template.html
<input formControlName="firstName" [readonly]='firstNameIsReadOnly'>
styles.scss
input[readonly] {
color: rgba(0,0,0,.38);
}
https://stackoverflow.com/questions/42180696
复制相似问题