html - Angular 2 : Forms with Material Design: ng-message doesn't work like it should

标签 html forms angular angular-material

因为我是 Angular2 的新手,所以我可能在处理从 .html 工作表到 .ts 文件的数据绑定(bind)时犯了一个错误,但我无法解决当前的问题。我有一个带有输入字段的表单,这个字段有 required -and maxlength-tag。当不遵循使用 Material Design 时,我有这些限制显示错误。我有一个按钮来发布输入。

<form name="postFeedForm">
      <table>
        <tr>
          <td class="long-td">
            <md-input-container class="md-block | long-inputfield">
              <input mdInput name="newDescription" [(ngModel)]="newDescription" #description placeholder="What's up?" required maxlength="150">
              <md-hint align="end">{{description.value.length}} / 150</md-hint>
              <div ng-messages="postFeedForm.description.$error" ng-show="postFeedForm.description.$dirty">
                <div ng-message="required">Please enter a description</div>
                <div ng-message="md-maxlength">Exceeded the maximum characters {{description.value.length}} / 150</div>
              </div>
            </md-input-container>
          </td>
          <td>
            <button md-button class="text-upper | spikes_red" type="submit" (click)="post()">Post</button>
          </td>
        </tr>
      </table>
    </form>

My result

我不确定“#description”标签,但没有它我会收到错误消息。问题是我遵循了不同的例子,我可能把它们混在一起了。我正在尝试做的事情可以在这里找到(包括代码笔):https://material.angularjs.org/latest/demo/input

Correct result

.ts 文件:

export class DashboardComponent {
  newDescription: string;

  post() {
    // Post some feed
    ...
    description: this.newDescription,
    ...
  }
}

来源:https://github.com/angular/material2/blob/master/src/demo-app/input/input-demo.html

最佳答案

现在有了“2.0.0-beta.3”,您可以使用“md-error”进行错误验证:

HTML:

<md-input-container>
    <input mdInput placeholder="email" [formControl]="emailFormControl" required>
    <md-error *ngIf="emailFormControl.hasError('required')">
    This field is required
    </md-error>
    <md-error *ngIf="emailFormControl.hasError('pattern')">
    Please enter a valid email address
    </md-error>
</md-input-container>

TS:

import { FormControl, Validators } from '@angular/forms';
...
const EMAIL_REGEX = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
....
export class PageComponent {
....
public emailFormControl = new FormControl('', [Validators.required, Validators.pattern(EMAIL_REGEX)]);
....
}

关于html - Angular 2 : Forms with Material Design: ng-message doesn't work like it should,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42691093/

相关文章:

javascript - 通过按键提交表单。但并非每次击键时

javascript - 使用 Angular 模板引用将动态值附加到动态文本字段

html - 无法在 div css 中编辑图像

html - Div "overflowing(?)"的内容到左侧和顶部

html - 在响应式网站中将子 div 垂直对齐到父 div

html - 如何将多个供应商前缀添加到一个 CSS 属性?

jquery - 如何像管理面板一样在 Django 中的外键中添加新项目?

forms - Twitter Bootstrap 表单 : Make label column wider

html - 如何在父 [Angular] 中两次调用的子组件上动态应用 CSS

angular - 如何使基本 href/IIS 虚拟目录对 Angular 应用程序不区分大小写?