【问题标题】:How to bind the value of disabled input in reactive form Angular 7如何以反应形式Angular 7绑定禁用输入的值
【发布时间】:2019-07-10 19:59:51
【问题描述】:

我无法绑定来自 FormGroup 的输入之一:

<input matInput placeholder="Center" value="Manila" formControlName="location" disabled>

它也没有被禁用。

当我插入[(ngModel)]="location" 以获取该值时,据说它已被删除或弃用。但输入被禁用。

我的表单(sn-p):

<mat-form-field class="tribe-full-width">
    <input matInput placeholder="Tribe Name" value="" formControlName="tribeName">
</mat-form-field>
<mat-form-field class="tribe-full-width">
    <input matInput placeholder="Tribe Leader Name" value="" formControlName="tribeLeader">
</mat-form-field>
<mat-form-field class="tribe-full-width">
    <input matInput placeholder="Center" value="Manila" formControlName="location">
</mat-form-field>

我的组件:

onSubmitTribeData() {
  console.log(this.tribeForm.value);
}

addTribe(){
  if (this.showForm === false) {
    this.showForm = true;
    this.tribeForm.controls['dtcLocation'].disable(); 
    this.tribeForm = this.fb.group({
      tribeName: [''],
      tribeLeader: [''],
      location: [''],
      tribeSquad: ['']
    });
  } else {
    this.showForm = false;
  }
}

【问题讨论】:

  • 你能在 stackblitz sn-p 中演示这个问题吗?
  • 显示值使用 myForm.getRawValue(),而不是 myForm.value:angular.io/api/forms/FormGroup#getRawValue,给出值使用 myForm.get('location').setValue(),并且永远不要一起使用[ngModel] 和 formControlName 在属于 formGroup 的变量上

标签: angular angular-reactive-forms formgroups


【解决方案1】:

假设你已经像这样设置你的响应式表单:

export class YourComponent {
  myForm = new FormGroup({
    location: new FormControl(''),
  });

  constructor() {}

  someFunction(): any {
    // You can access the value of an input as follows:
    const value = this.myForm.get('location').value;
  }
}

您可以通过[attr.disabled] 禁用模板中的输入:

<input matInput [attr.disabled]="true" placeholder="Center" value="DTC Manila" formControlName="location">

或者您可以在组件中以编程方式执行此操作:

this.myForm.controls['location'].disable(); 
this.myForm.controls['location'].enable(); // To re-enable the input.

注意:[(ngModel)] 不应与反应形式一起使用 support for using the ngModel input property and ngModelChange event with reactive form directives has been deprecated in Angular v6 and was removed in Angular v7.

【讨论】:

  • 如果location 总是被禁用,你可以像这样初始化它:location: new FormControl({value: '', disabled: true})
  • 嗨,我编辑了我的帖子。请检查一下。我还使用了 [attr.disabled]="true" 和 this.myForm.controls['location'].disable();但它没有用
  • @Mark - 此答案中概述的步骤是您当前如何禁用 Angular 反应形式中的输入。为了让我们进一步提供帮助,您需要提供 Minimal, Reproducible Example 来说明您遇到的问题。
【解决方案2】:

试试这个;

this.formGroup.controls['controlName'].setValue(value);

请避免在反应形式中使用disabled 属性。您可以使用以下方法初始化控件;

new FormControl({value: '', disabled: true})

或者在你想禁用控件的地方使用它;

this.formGroup.controls['controlName'].disable();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-10
    • 2019-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-07
    • 2018-12-19
    • 2019-11-26
    相关资源
    最近更新 更多