如何禁用表单控件但保持值

Tam*_*mpa 22 angular

我有一个反应形式.在编辑时我想要禁用控件.

以下作品:

   this.myForm.controls['analysis_horizon'].disable();
Run Code Online (Sandbox Code Playgroud)

但是,关键的analysis_horizo​​n不再是我的myForm.value哈希.

如何禁用具有被动形式的字段,但将值保留在表单值哈希中?

我试过[禁用] =但我得到以下内容:

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)
      });
Run Code Online (Sandbox Code Playgroud)

我在编辑时将数据从编辑中加载到表单控件中,但我需要一个字段不允许更改.

小智 39

您可以使用getRawValue()而不是value属性.根据文件:

FormGroup的聚合值,包括任何已禁用的控件.

如果您想要包括所有值而不管禁用状态,请使用此方法.否则,value属性是获取组值的最佳方式.

this.myForm.getRawValue()
Run Code Online (Sandbox Code Playgroud)


小智 7

我的解决方案是使用 [attr.disabled]:

<select formControlName="foo"
  [attr.disabled]="disabled == true ? true : null"> 
</select>
Run Code Online (Sandbox Code Playgroud)

假设您的组件中有一个 disabled 属性。您必须返回 null 而不是 false 才能启用输入。

  • 尽管在这种情况下 Angular 没有发出警告,但它仍然使应用程序容易受到“检查后更改”错误的影响。 (3认同)

小智 7

尝试添加onlySelf: true内部方法禁用:

this.myForm.controls['analysis_horizon'].disable({onlySelf: true});
Run Code Online (Sandbox Code Playgroud)

  • 这并没有达到预期的效果。它还禁用表单控制。 (6认同)

Ant*_*ony 6

如果您不想使用 getRawValue 更改从表单获取值的正常方式,则这是另一种选择。我更喜欢 readonly 的更多原因:https : //stackoverflow.com/a/7730719/1678151

我的解决方案还展示了如何填充表单控件。

组件.ts

fillForm(data: any){
 if (data != null && data.firstName){
   this.form.patchValue({
     firstName: data.firstName
   })    
   this.firstNameIsReadOnly = true;
 } 
Run Code Online (Sandbox Code Playgroud)

模板.html

<input formControlName="firstName" [readonly]='firstNameIsReadOnly'>
Run Code Online (Sandbox Code Playgroud)

样式.scss

input[readonly] {
 color: rgba(0,0,0,.38);
}
Run Code Online (Sandbox Code Playgroud)