【问题标题】:mat-error doesn't show inside mat-form-fieldmat-error 不显示在 mat-form-field 内
【发布时间】:2020-10-08 18:09:58
【问题描述】:

DEMO

我在子组件中有 mat-select 代码,我通过输入来显示和隐藏错误。下面是我的代码,

  <mat-form-field>
    <mat-select [formControl]="ctrl" [placeholder]="placeholder">
      <mat-option *ngFor="let option of options" [value]="option">
        {{ option }}
      </mat-option>
    </mat-select>
    <mat-error *ngIf="onError">Error: Required Field</mat-error>
  </mat-form-field>

onError 是一个输入属性,决定隐藏或显示 mat 错误。

下面是我如何调用 mat-select

<my-select onError="true" [ctrl]="form.get('cities')" [options]="cities" placeholder="Cities"></my-select>

【问题讨论】:

    标签: angular angular-material


    【解决方案1】:

    Stackblitz :https://stackblitz.com/edit/custom-mat-select-nfpb1x?file=app/app.component.ts

    export class AppComponent  {
      form: FormGroup;
    
      cities = ['','Krakow', 'Warszawa', 'Gdansk'];
      countries = ['Poland', 'Germany', 'Sweden'];
    
      constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
          cities: ['', Validators.required],
          countries: ['', Validators.required],
        })
      }
    }
    

    只需添加空选择,因为如果值为空,则会出现错误。

    【讨论】:

    • 如果您将 mat-error 放在 mat-form-field 之外但不在其中,它会起作用。您不需要空字符串,只需单击任何选项。它会工作
    • 但是这个验证是为了不选择有效的输入权?
    • 我将触发 markastouched 方法,但如果它在 mat-select 内,它们将不起作用
    • cities: ['', Validators.required], 有空时会报错
    • 我的链接已更新。问题在于 ng 值访问器
    【解决方案2】:

    除了aviby2006s为空,您还可以在模板中添加空选项,这样您的选项数组就可以保留没有空选项:

    <mat-select [formControl]="ctrl" [placeholder]="placeholder">
      <mat-option value=""></mat-option>
      <mat-option *ngFor="let option of options" [value]="option">
         {{ option }}
       </mat-option>
    </mat-select>
    

    【讨论】:

    • 您不需要空选项或空字符串来使其工作。只需单击选择框,不要选择任何选项。
    【解决方案3】:

    两件事:

    1.- 你忘了告诉你的组件选择是[formControl]

    <mat-select [formControl]="ctrl" [placeholder]="placeholder">
        ...
    </mat-select>
    

    2.- 当您作为[ctrl] 传递自己的 formControl 时,您不需要实现 ControlValueAccessor(它仅在您创建自定义表单控件时使用 - 一个“特殊组件”,您可以在 ReactiveForm 中使用或使用将 [(ngModel)] 用作普通的&lt;input&gt;-。我想说的是删除函数:writeValue、registerOnChange、...

    【讨论】:

      猜你喜欢
      • 2020-02-23
      • 1970-01-01
      • 2020-10-26
      • 1970-01-01
      • 2018-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-29
      相关资源
      最近更新 更多