问题描述
我在组件中有一个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
输入不再被禁用(此输入的值已被正确更新)。
测试过的无效解决方案:
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;
}