如何以反应形式Angular 7绑定禁用输入的值

时间:2019-07-10 07:08:12

标签: angular angular-reactive-forms formgroups

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

router := httprouter.New()
// register prometheus exporter 
go func() {
    http.Handle("/metrics", promhttp.Handler())
    http.ListenAndServe(":8080", nil)
}()
http.ListenAndServe(":80", router)

它也不被禁用。

当我插入<input matInput placeholder="Center" value="Manila" formControlName="location" disabled> 以便获取值时,据说该值已被删除或弃用。输入已被禁用。

我的表单(摘要):

[(ngModel)]="location"

我的组件:

<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>

2 个答案:

答案 0 :(得分:0)

假设您已经设置了这样的反应形式:

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.等反应形式一起使用

答案 1 :(得分:-1)

尝试一下;

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

请避免将disabled属性与反应形式一起使用。您可以使用来初始化控件;

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

或在您要禁用该控件的位置使用它;

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