我正在创建一个带有mat-select的反应形式。
<mat-form-field>
<mat-select placeholder="Salutation*" formControlName="salutation">
<mat-option *ngFor="let salutation of salutations" [value]="salutation.id">
{{ salutation.label }}
</mat-option>
</mat-select>
</mat-form-field>
形成:
this.form = this.fb.group({
person: this.fb.group({
salutation: ['', Validators.required],
firstName: ['', Validators.required],
lastName: ['', Validators.required],
email: ['', Validators.required]
})
});
我需要根据其他输入值禁用/启用此选择。由于反应形式不再支持[禁用],因此我使用了以下内容
this.form.get('person').get('salutation').disable();
问题是当我尝试启用选择返回时
this.form.get('person').get('salutation').enable();
它只是不起作用。有什么想法吗?
PS:使用disabled属性工作正常,但它会发出警告
看起来您正在使用带有响应式表单指令的disabled属性。如果在组件类中设置此控件时将disabled设置为true,则实际将在DOM中为您设置disabled属性。我们建议使用此方法来避免“检查后更改”错误。
Example:
form = new FormGroup({
first: new FormControl({value: 'Nancy', disabled: true}, Validators.required),
last: new FormControl('Drew', Validators.required)
});
谢谢!
我没有看到你从哪里获得你的地址。除了查看以下作品的地址。
email: ['', [Validators.required]]
<form [formGroup]="form">
<div formGroupName="person">
<mat-form-field>
<mat-select placeholder="Salutation*" formControlName="salutation">
<mat-option *ngFor="let salutation of salutations" [value]="salutation.id">
{{ salutation.label }}
</mat-option>
</mat-select>
</mat-form-field>
</div>
</form>
ngOnInit() {
this.form = this.fb.group({
person: this.fb.group({
salutation: [{value: '', disabled: true}],
firstName: ['', Validators.required],
lastName: ['', Validators.required],
email: ['', [Validators.required]]
})
});
this.form.get('person').get('salutation').enable();
}
当我尝试重新初始化窗体并将控件设置为启用时,我遇到了这个问题。 (场景显示的细节记录只能由该记录的所有者编辑)。除了select控件之外,这适用于大多数控件。我设法通过使用适合您的代码的以下解决方案:
this.form.controls["salutation"].enable();