英文:
How do I disable mat-form-field with a conditional value?
问题
这是我的代码:
<mat-form-field [disabled]="isDisabled">
这个代码部分不需要翻译。
这个错误提示是:
无法绑定到 'disabled',因为它不是 'mat-form-field' 的已知属性。
更新:
这是我解决它的方式。在我的情况下,我实际上需要禁用整个表单,而不仅仅是单个字段。
HTML:
<mat-form-field [formGroup]="myForm">
<mat-select formControlName="myControl">
<mat-option>我的第一个选项</mat-option>
<mat-option>我的第二个选项</mat-option>
</mat-select>
</mat-form-field>
JS:
// 声明表单
myForm: FormGroup;
ngOnInit() {
this.myForm = this.formBuilder.group({
myControl: ['']
});
this.myForm.disable();
}
// 使用 enable 和 disable 方法在不同状态之间切换
if (myCondition) {
this.myForm.enable();
}
else {
this.myForm.disable();
}
这部分内容不需要翻译。
英文:
This is my code:
<mat-form-field [disabled]="isDisabled">
Which gives me the error:
Can't bind to 'disabled' since it isn't a known property of 'mat-form-field'.
UPDATE:
This is how I solved it. In my case, I actually needed to disable the whole form rather than just the single field.
HTML:
<mat-form-field [formGroup]="myForm">
<mat-select formControlName="myControl">
<mat-option>my first option</mat-option>
<mat-option>my second option</mat-option>
</mat-select>
</mat-form-field>
JS:
//declare the form
myForm: FormGroup;
ngOnInit() {
this.myForm = this.formBuilder.group({
myControl: ['']
});
this.myForm.disable();
}
// use the enable and disable methods to toggle between states
if (myCondition) {
this.myForm.enable();
}
else {
this.myForm.disable();
}
答案1
得分: 0
如果您的表单是响应式的,那么上面的<mat-form-field [disabled]="isDisabled">
将不起作用。
您需要根据条件使用this.formGroupName.controls[controlName].disable()
来禁用它。
英文:
If your form is reactive then the above <mat-form-field [disabled]="isDisabled">
will not work.
You need disable it using this.formGroupName.controls[controlName].disable()
conditionally.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论