Angular 10 : input example
Angular 10 : input example
matInput is a directive that allows native <input> and <textarea> elements to work with <mat-form-field>.
<input> and <textarea> attributes
All of the attributes that can be used with normal <input> and <textarea> elements can be used on elements inside <mat-form-field> as well. This includes Angular directives such as ngModel and formControl.The only limitation is that the type attribute can only be one of the values supported by matInput.
Supported <input> types
The following input types can be used with matInput:- color
- date
- datetime-local
- month
- number
- password
- search
- tel
- text
- time
- url
- week
HTML:
<form class="example-form"><mat-form-field class="example-full-width">
<mat-label>Email</mat-label>
<input matInput [formControl]="emailFormControl" [errorStateMatcher]="matcher"
placeholder="Ex. pat@example.com">
<mat-hint>Errors appear instantly!</mat-hint>
<mat-error *ngIf="emailFormControl.hasError('email') && !emailFormControl.hasError('required')">
Please enter a valid email address
</mat-error>
<mat-error *ngIf="emailFormControl.hasError('required')">
Email is <strong>required</strong>
</mat-error>
</mat-form-field>
</form>
TS/JavaScript:
import {Component} from '@angular/core';import {FormControl, FormGroupDirective, NgForm, Validators} from '@angular/forms';
import {ErrorStateMatcher} from '@angular/material/core';
/** Error when invalid control is dirty, touched, or submitted. */
export class MyErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
const isSubmitted = form && form.submitted;
return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));
}
}
/** @title Input with a custom ErrorStateMatcher */
@Component({
selector: 'input-error-state-matcher-example',
templateUrl: './input-error-state-matcher-example.html',
styleUrls: ['./input-error-state-matcher-example.css'],
})
export class InputErrorStateMatcherExample {
emailFormControl = new FormControl('', [
Validators.required,
Validators.email,
]);
matcher = new MyErrorStateMatcher();
}
Comments
Post a Comment