【问题标题】:How to show md-error in material select box in angular 2?如何在角度 2 的材料选择框中显示 md-error?
【发布时间】:2017-11-24 07:47:42
【问题描述】:

我在我的 Angular 2 项目中使用响应式表单进行验证。我想突出显示按下“提交”时无效的字段。我已经通过使用 md-Error 在输入标签中实现了这一点,但我无法在 md-Select 中做到这一点。有人可以帮忙吗?

截图:http://i.imgur.com/uOQbwaZ.png

这是我正在使用的 md-select 示例:

<md-select placeholder="Listing Type" formControlName='listingType' required >
              <md-option *ngFor="let type of listType" [value]="type">
                {{ type }}
              </md-option>
            </md-select>

这是我正在使用的 md 输入:

<md-input-container class="more-width">
              <input mdInput formControlName='price' required placeholder="Price">
              <md-error>Please Enter Price</md-error>
            </md-input-container>

这是我正在应用的验证

 this.listingForm = this.fb.group({
      propertyType: ['', Validators.required]
})

【问题讨论】:

  • 请贴一些代码。
  • 用代码示例更新了帖子
  • 这在 plunker 中工作正常,但是当我在 VS Code 中使用它时,没有选择默认值
  • 嗨!你解决了这个问题吗?

标签: angular material-design angular-material angular2-forms


【解决方案1】:

您可以在框下方显示红线,但目前没有错误消息。我认为这是一个很快就会出现的功能。 Issue on Github

【讨论】:

    【解决方案2】:

    您可以在角度材料文档here 中找到验证电子邮件地址的一个很好的示例。

    【讨论】:

      【解决方案3】:

      此错误现已解决。您只需将mat-error 放在mat-select 之外和mat-form-field 之内。这是一个例子

      <mat-form-field appearance="fill">
        <mat-label>Favorite animal</mat-label>
         <mat-select [formControl]="animalControl" required>
          <mat-option>--</mat-option>
          <mat-option *ngFor="let animal of animals" [value]="animal">
            {{animal.name}}
          </mat-option>
        </mat-select>
        <mat-error *ngIf="animalControl.hasError('required')">Please choose an 
            animal</mat-error>
      </mat-form-field>
      

      详情可以查看以下链接 Error Messages in Angular form fields

      【讨论】:

      • 请阅读How to Answer。虽然此链接的内容实际上可能解决问题,但本网站不鼓励仅提供链接的答案。链接往往会中断,然后答案就失去了价值。最好将链接的基本部分作为文本包含在答案本身中,并提供链接作为参考。您的纯文本答案如下所示:PLease check the following link. Angular Material Select Box,它没有提供太多信息。如果您认为单独的链接可以提供帮助,请将其作为评论发布(如果您有 50 个代表)。
      猜你喜欢
      • 2018-03-08
      • 2020-06-17
      • 2017-12-29
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 2019-08-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多