I am creating a form with Angular Material 2. I am using template driven form and I have email input which has two validators (required and email). In the doc for the input component (https://material.angular.io/components/component/input) it only says:
"If an input element can have more than one error state, it is up to the consumer to toggle which messages should be displayed. This can be done with CSS, ngIf or ngSwitch."
there is no example and I can't find it anywhere.
This is my html:
...
<form (ngSubmit)="onSubmit(registrationForm)" #registrationForm="ngForm">
...
<md-input-container floatPlaceholder="never">
<input mdInput type="email" placeholder="Enter your email address" name="email" [(ngModel)]="email" required email>
<md-error class="required">Email is required.</md-error>
<md-error class="email">Invalid email.</md-error>
</md-input-container>
...
Currently both messages are shown all the time. Even if I enter some invalid email.
Any of the mentioned solutions (CSS, ngIf or ngSwitch) would be fine but I'd prefer CSS.
This is how i have implemented it in Angular 6 (ReactiveFormsModule
)
HTML
<form [formGroup]="service.form" class="normal-form">
<mat-grid-list cols="2" rowHeight="300px">
<mat-grid-tile>
<input type="hidden" formControlName="$key">
<div class="controles-container">
<mat-form-field>
<input formControlName="mobile" matInput placeholder="Mobile*">
<mat-error *ngIf="service.form.controls['mobile'].errors?.required">This field is mandatory.</mat-error>
<mat-error *ngIf="service.form.controls['mobile'].errors?.minlength">Minimum 8 charactors needed.</mat-error>
</mat-form-field>
</div>
</mat-grid-tile>
</mat-grid-list>
</form>
Component.ts
export class MyComponent implements OnInit {
constructor(public service :EmployeeService) { }
ngOnInit() {
}
onClear() {
this.service.form.reset();
}
}
Service
export class EmployeeService {
constructor() { }
form :FormGroup = new FormGroup({
$key :new FormControl(null),
mobile:new FormControl('',[Validators.required,Validators.minLength(10)]),
});
}
See example below. A great way to get working examples is to review/search the Angular 2 Material GIT repo. Example below comes from https://github.com/angular/material2/blob/master/src/demo-app/input/input-demo.html
<md-input-container>
<input mdInput placeholder="email" [formControl]="emailFormControl">
<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>
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