角度8:FormGroup更新后,物料输入未禁用

问题描述

我在组件中有一个FormGroup,并使用来自父组件的数据进行了初始化。这是我的子组件中的初始化:

<mat-form-field class="fluid">
   <mat-label>Prénom</mat-label>
   <input matInput formControlName="firstname" type="text" placeholder="Prénom" required />
</mat-form-field>
ngOnChanges(changes: SimpleChanges) {
   this.form = this.fb.group({
      firstname: [this.currentParticipant.username,Validators.required])
   })

   // ...
   this.form.controls.firstname.disable()
}

我希望我的输入被禁用。单击父组件按钮后,数据将更新并发送到我的子组件。在更新的表单上,firstname输入不再被禁用(此输入的值已被正确更新)。

测试过的无效解决方案:

    模板中的
  • [attr.disabled]="true"[disabled]="true"属性
  • 在formGroup初始化上设置禁用的属性
this.form = this.fb.group({
      firstname: [{ value: this.currentParticipant.username,disabled: true },Validators.required])
   })

您对发生的事情有想法吗?

解决方法

您可以像这样使用[disabled]属性:

HTML:

<mat-form-field class="fluid" [ngClass]="mainColor">
   <mat-label>Prénom</mat-label>
   <input matInput [disabled]="somevariable" formControlName="firstname" type="text" placeholder="Prénom" required />
</mat-form-field>

TS文件:

ngOnChanges(changes: SimpleChanges) {
   this.form = this.fb.group({
      firstname: [this.currentParticipant.username,Validators.required])
   })

   // ...
   somevariable = true;
}