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

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

How do I disable mat-form-field with a conditional value?

问题

这是我的代码:

  1. <mat-form-field [disabled]="isDisabled">

这个代码部分不需要翻译。

这个错误提示是:

  1. 无法绑定到 'disabled',因为它不是 'mat-form-field' 的已知属性。

更新:

这是我解决它的方式。在我的情况下,我实际上需要禁用整个表单,而不仅仅是单个字段。

HTML:

  1. <mat-form-field [formGroup]="myForm">
  2. <mat-select formControlName="myControl">
  3. <mat-option>我的第一个选项</mat-option>
  4. <mat-option>我的第二个选项</mat-option>
  5. </mat-select>
  6. </mat-form-field>

JS:

  1. // 声明表单
  2. myForm: FormGroup;
  3. ngOnInit() {
  4. this.myForm = this.formBuilder.group({
  5. myControl: ['']
  6. });
  7. this.myForm.disable();
  8. }
  9. // 使用 enable 和 disable 方法在不同状态之间切换
  10. if (myCondition) {
  11. this.myForm.enable();
  12. }
  13. else {
  14. this.myForm.disable();
  15. }

这部分内容不需要翻译。

英文:

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:

  1. &lt;mat-form-field [formGroup]=&quot;myForm&quot;&gt;
  2. &lt;mat-select formControlName=&quot;myControl&quot;&gt;
  3. &lt;mat-option&gt;my first option&lt;/mat-option&gt;
  4. &lt;mat-option&gt;my second option&lt;/mat-option&gt;
  5. &lt;/mat-select&gt;
  6. &lt;/mat-form-field&gt;

JS:

  1. //declare the form
  2. myForm: FormGroup;
  3. ngOnInit() {
  4. this.myForm = this.formBuilder.group({
  5. myControl: [&#39;&#39;]
  6. });
  7. this.myForm.disable();
  8. }
  9. // use the enable and disable methods to toggle between states
  10. if (myCondition) {
  11. this.myForm.enable();
  12. }
  13. else {
  14. this.myForm.disable();
  15. }

答案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:

确定