Because I'm fairly new with Angular2 I've probably made a mistake to do with data binding from the .html sheet to the .ts file but I can't work the current problem out. I have a form with an input field and this field has the required -and maxlength-tag. I have these restrictions display an error when not followed by using Material Design. And I have a button to post the input.
<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>

I'm not sure about the "#description"-tag but without it I get an error. The problem is that I've followed different examples and I probably mixed them up. What I'm trying to do can be found here (including Code Pen): https://material.angularjs.org/latest/demo/input

The .ts file:
export class DashboardComponent {
newDescription: string;
post() {
// Post some feed
...
description: this.newDescription,
...
}
}
Source: https://github.com/angular/material2/blob/master/src/demo-app/input/input-demo.html
Now with "2.0.0-beta.3" you can use 'md-error' for error validation:
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)]);
....
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With