如何使用条件值禁用mat-form-field?

huangapple go评论60阅读模式
英文:

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:

&lt;mat-form-field [formGroup]=&quot;myForm&quot;&gt;
    &lt;mat-select formControlName=&quot;myControl&quot;&gt;
        &lt;mat-option&gt;my first option&lt;/mat-option&gt;
        &lt;mat-option&gt;my second option&lt;/mat-option&gt;
    &lt;/mat-select&gt;
&lt;/mat-form-field&gt;

JS:

//declare the form
myForm: FormGroup;

ngOnInit() {
    this.myForm = this.formBuilder.group({
        myControl: [&#39;&#39;]
    });
    this.myForm.disable();
}

// use the enable and disable methods to toggle between states
if (myCondition) {
    this.myForm.enable();
}
else {
    this.myForm.disable();
}

答案1

得分: 0

如果您的表单是响应式的,那么上面的&lt;mat-form-field [disabled]=&quot;isDisabled&quot;&gt;将不起作用。

您需要根据条件使用this.formGroupName.controls[controlName].disable()来禁用它。

英文:

If your form is reactive then the above &lt;mat-form-field [disabled]=&quot;isDisabled&quot;&gt; will not work.

You need disable it using this.formGroupName.controls[controlName].disable()
conditionally.

huangapple
  • 本文由 发表于 2023年7月18日 02:17:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76707130.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定