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