How To Make A Textarea Register Tab Angular 2
Angular Material Textarea
September 05, 2018
This page will walk through Angular Material textarea instance. Athwart Fabric provides MatInput Directive to create <input> and <textarea> element with a MatFormField. To use MatInput nosotros demand to import MatInputModule in awarding module. MatInput provides errorStateMatcher property to assign ErrorStateMatcher object to control when to show validation error.
Athwart Component Dev Kit (CDK) provides CdkTextareaAutosize Directive to automatically resize a textarea to fit its content. Information technology provides cdkTextareaAutosize property to enable autosizing, cdkAutosizeMinRows property to define minimum amount of rows and cdkAutosizeMaxRows belongings to define maximum amount of rows in the textarea for autosizing. CdkTextareaAutosize likewise provides resizeToFitContent() method to resize the text area to fit its content and reset() method to reset the textarea to original size.
On this page we volition create Angular Fabric textarea and validate it. We volition use CdkTextareaAutosize Directive for autosizing and volition create reactive and template-driven forms with Angular Material textarea.
Contents
- Technologies Used
- Import MatInputModule
- Utilise MatInput to create Textarea
- Validation
- Using Custom ErrorStateMatcher
- Using CdkTextareaAutosize
- Create readonly Textarea
- Reactive Course Example using Textarea
- Template-Driven Course Example using Textarea
- Run Application
- References
- Download Source Code
Technologies Used
Observe the technologies beingness used in our example.
i. Angular 6.1.0
two. Angular CLI 6.1.three
3. Angular Material half-dozen.4.vii
4. TypeScript ii.vii.two
5. Node.js 10.3.0
6. NPM 6.one.0
Import MatInputModule
To work with Angular Material <input> and <textarea>, we need to import MatInputModule in application module.
import { MatInputModule } from '@angular/material/input'; @NgModule({ imports: [ ------ MatInputModule ], ------ }) export class AppModule { } Use MatInput to create Textarea
Angular Material uses MatInput Directive to create <input> and <textarea> inside a <mat-form-field>. MatInput Directive selector is matInput. Find the code snippet to create a <textarea> using matInput selector.
<mat-form-field> <textarea matInput placeholder="Comment" [formControl]="commentFC" (change)="onCommentChange()"> </textarea> </mat-form-field>
Find the code snippet for TS.
commentFC = new FormControl(); onCommentChange() { panel.log(this.commentFC.value); } MatInput has post-obit backdrop.
errorStateMatcher: This is ErrorStateMatcher object to control when error messages are shown.
readonly: This is Boolean value to know if element is readonly.
blazon: Information technology gives input type of the chemical element.
errorState: This is Boolean value to know if control is in error land or not.
Validation
To apply validation on <textarea> input, nosotros can employ Athwart Validators equally usual. Observe the code snippet of TS file.
commentFC = new FormControl('', [ Validators.required, Validators.maxLength(xxx) ]); Find the code snippet to create <textarea> in HTML template.
<mat-grade-field> <textarea matInput placeholder="Comment" [formControl]="commentFC" (change)="onCommentChange()"> </textarea> <mat-mistake *ngIf="commentFC.hasError('required')"> Comment is required. </mat-error> <mat-error *ngIf="commentFC.hasError('maxlength')"> Max length is 30. </mat-error> </mat-form-field> Mistake messages are shown using mat-error and mat-form-field associates error messages with matInput. By default errors are shown in the country of invalid command, touched or form submitted. We tin use custom ErrorStateMatcher to change default behavior when to bear witness error.
Using Custom ErrorStateMatcher
Angular Material provides ErrorStateMatcher to command when to show fault. It has isErrorState() method that accepts FormControl and FormGroupDirective or NgForm as arguments and returns Boolean. To create custom ErrorStateMatcher form, nosotros need to implement ErrorStateMatcher and override isErrorState(). If isErrorState() returns true, error will be shown and if false then error will non be shown. To use it with <input> and <textarea> input, MatInput Directive provides errorStateMatcher holding. We demand to assign the object of custom ErrorStateMatcher to errorStateMatcher property. Find our custom ErrorStateMatcher.
custom-fault-land-matcher.ts
import { ErrorStateMatcher } from '@angular/textile/cadre'; import { FormControl, FormGroupDirective, NgForm } from '@angular/forms'; export class CustomErrorStateMatcher implements ErrorStateMatcher { isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | cypher): boolean { const isSubmitted = grade && course.submitted; return (command.invalid && (command.dirty || control.touched || isSubmitted)); } } Our custom ErrorStateMatcher can exist used for a <input> and <textarea> using errorStateMatcher belongings or globally for every <input> and <textarea> in the application.
a. To utilize errorStateMatcher property, we will create an instance of CustomErrorStateMatcher in TS file.
esMatcher = new CustomErrorStateMatcher();
Now employ esMatcher object with errorStateMatcher property.
<mat-form-field> <textarea matInput placeholder="Comment" [formControl]="commentFC" [errorStateMatcher]="esMatcher" (change)="onCommentChange()"> </textarea> <mat-mistake *ngIf="commentFC.hasError('required')"> Comment is required. </mat-error> <mat-error *ngIf="commentFC.hasError('maxlength')"> Max length is thirty. </mat-error> </mat-course-field> b. To use custom ErrorStateMatcher globally, configure provider in application module as following.
providers: [ {provide: ErrorStateMatcher, useClass: CustomErrorStateMatcher} ] At present CustomErrorStateMatcher will be applied to all <input> and <textarea> chemical element in the application. Angular material likewise provides ShowOnDirtyErrorStateMatcher that matches when a command is invalid and muddy.
Using CdkTextareaAutosize
CdkTextareaAutosize Directive is used to automatically resize a textarea to fit its content. Component Dev Kit (CDK) provides high quality predefined behavior for the components. CDK allows the states to add together common interaction patterns with minimal effort.
Find the CdkTextareaAutosize properties to utilize with textarea.
one. cdkTextareaAutosize
It defines whether autosizing is enabled or not. cdkTextareaAutosize is used with <textarea> element. It is declared in CdkTextareaAutosize Directive equally following.
@Input('cdkTextareaAutosize') go enabled(): boolean { return this._enabled; } We can use enabled property in TS file to know if autosize is enabled or non.
ii. cdkAutosizeMinRows
It defines minimum amount of rows in the textarea for autosizing. cdkAutosizeMinRows is used with <textarea> element. It is declared in CdkTextareaAutosize Directive as following.
@Input('cdkAutosizeMinRows') get minRows(): number { return this._minRows; } We tin can use minRows property in TS file to go configured autosize minimum rows.
three. cdkAutosizeMaxRows
It defines maximum amount of rows in the textarea for autosizing. cdkAutosizeMaxRows is used with <textarea> element. Information technology is declared in CdkTextareaAutosize Directive equally following.
@Input('cdkAutosizeMaxRows') get maxRows(): number { return this._maxRows; } We can utilize maxRows belongings in TS file to go configured autosize maximum rows.
Now find the sample case of textarea with autosize configurations.
<mat-form-field> <textarea matInput placeholder="Description" [formControl]="descFC" cdkTextareaAutosize cdkAutosizeMinRows="two" cdkAutosizeMaxRows="5" #autosize="cdkTextareaAutosize" (change)="onDescChange()"> </textarea> <mat-error *ngIf="descFC.hasError('required')"> Clarification is required. </mat-error> </mat-form-field> Find the TS file lawmaking snippet.
descFC = new FormControl('', [ Validators.required ]); @ViewChild('autosize') txtAreaAutosize: CdkTextareaAutosize; onDescChange() { panel.log("enabled: "+ this.txtAreaAutosize.enabled); console.log("minRows: "+ this.txtAreaAutosize.minRows); console.log("maxRows: "+ this.txtAreaAutosize.maxRows); console.log("Clarification: "+ this.descFC.value); } 4. resizeToFitContent()
resizeToFitContent() method of CdkTextareaAutosize is used to resize the text area to fit its content. It accepts Boolean value. By passing true we tin force a acme calculation. By default, acme calculation is performed only when value changed since the concluding call.
five. reset()
reset() method of CdkTextareaAutosize resets the textarea to original size. When nosotros configure cdkAutosizeMinRows and cdkAutosizeMaxRows in textarea, it is car resized. On calling reset(), textarea resizes to its original size.
Find the HTML lawmaking snippet to exam resizeToFitContent() and reset().
<div> <mat-grade-field [style.fontSize]="fontSize.value"> <textarea matInput placeholder="Content" [formControl]="contentFC" cdkTextareaAutosize cdkAutosizeMinRows="ii" cdkAutosizeMaxRows="five" #cfcAutosize="cdkTextareaAutosize"> </textarea> </mat-form-field> </div> <div> <push button mat-push (click)="resetTextAreaSize()">Reset Textarea Size</button> </div> <br/> <div> <mat-form-field> <mat-label>Select Font size</mat-label> <mat-select #fontSize value="15px" (selectionChange)="resizeTextArea()"> <mat-pick value="10px">10px</mat-option> <mat-option value="15px">15px</mat-option> <mat-pick value="20px">20px</mat-option> </mat-select> </mat-form-field> </div>
Find the TS file lawmaking snippet.
constructor(private ngZone: NgZone) {} contentFC = new FormControl(); @ViewChild('cfcAutosize') contentFCAutosize: CdkTextareaAutosize; resizeTextArea() { this.ngZone.onStable.pipage(have(i)) .subscribe(() => this.contentFCAutosize.resizeToFitContent(true)); } resetTextAreaSize() { this.contentFCAutosize.reset(); } NgZone is an injectable service for executing work inside or exterior of the Athwart zone.
Create readonly Textarea
To create a readonly textarea, use readonly belongings with <textarea> element.
<mat-form-field> <textarea matInput readonly cdkTextareaAutosize cdkAutosizeMinRows="ii" cdkAutosizeMaxRows="five"> Text Line 1 Text Line 2 Text Line three </textarea> </mat-form-field>
Reactive Course Example using Textarea
Discover the consummate code to create textarea using reactive form.
reactive-class.component.html
<h4>1. Textarea validation</h4> <div> <mat-form-field> <textarea matInput placeholder="Comment" [formControl]="commentFC" [errorStateMatcher]="esMatcher" (modify)="onCommentChange()"> </textarea> <mat-error *ngIf="commentFC.hasError('required')"> Comment is required. </mat-error> <mat-error *ngIf="commentFC.hasError('maxlength')"> Max length is 30. </mat-error> </mat-grade-field> </div> <h4>2. Textarea autosize</h4> <div> <mat-grade-field> <textarea matInput placeholder="Description" [formControl]="descFC" cdkTextareaAutosize cdkAutosizeMinRows="ii" cdkAutosizeMaxRows="5" #autosize="cdkTextareaAutosize" (alter)="onDescChange()"> </textarea> <mat-fault *ngIf="descFC.hasError('required')"> Clarification is required. </mat-fault> </mat-grade-field> </div> <h4>three. resizeToFitContent() and Reset() test</h4> <div> <mat-form-field [style.fontSize]="fontSize.value"> <textarea matInput placeholder="Content" [formControl]="contentFC" cdkTextareaAutosize cdkAutosizeMinRows="two" cdkAutosizeMaxRows="5" #cfcAutosize="cdkTextareaAutosize"> </textarea> </mat-grade-field> </div> <div> <push mat-raised-button (click)="resetTextAreaSize()">Reset Textarea Size</button> </div> <br/> <div> <mat-form-field> <mat-label>Select Font size</mat-label> <mat-select #fontSize value="15px" (selectionChange)="resizeTextArea()"> <mat-selection value="10px">10px</mat-option> <mat-option value="15px">15px</mat-option> <mat-option value="20px">20px</mat-option> </mat-select> </mat-class-field> </div> <h4>four. Person Reactive Grade</h4> <form [formGroup]="personForm" (ngSubmit)="onFormSubmit()"> <div> <mat-form-field> <input matInput placeholder="Name" formControlName="name" [errorStateMatcher]="esMatcher"> <mat-error *ngIf="name.hasError('required')"> Name is required. </mat-mistake> </mat-form-field> </div> <div> <mat-form-field> <textarea matInput placeholder="Address" formControlName="address" cdkTextareaAutosize cdkAutosizeMinRows="two" cdkAutosizeMaxRows="4" [errorStateMatcher]="esMatcher"> </textarea> <mat-mistake *ngIf="address.hasError('required')"> Comment is required. </mat-error> <mat-error *ngIf="accost.hasError('maxlength')"> Max length is 100. </mat-error> </mat-form-field> </div> <div> <button mat-raised-push>Submit</push> </div> </form> reactive-form.component.ts
import { Component, OnInit, ViewChild, NgZone } from '@angular/core'; import { FormControl, Validators, FormBuilder } from '@athwart/forms'; import { CdkTextareaAutosize } from '@angular/cdk/text-field'; import { take } from 'rxjs/operators'; import { CustomErrorStateMatcher } from './custom-error-country-matcher'; import { PersonService } from './person.service'; @Component({ selector: 'app-reactive', templateUrl: './reactive-form.component.html' }) export class ReactiveFormComponent implements OnInit { constructor(private ngZone: NgZone, private formBuilder: FormBuilder, individual personService: PersonService) {} ngOnInit() { } //Textarea validation esMatcher = new CustomErrorStateMatcher(); commentFC = new FormControl('', [ Validators.required, Validators.maxLength(30) ]); onCommentChange() { console.log(this.commentFC.value); } //Textarea autosize descFC = new FormControl('', [ Validators.required ]); @ViewChild('autosize') txtAreaAutosize: CdkTextareaAutosize; onDescChange() { console.log("enabled: "+ this.txtAreaAutosize.enabled); console.log("minRows: "+ this.txtAreaAutosize.minRows); panel.log("maxRows: "+ this.txtAreaAutosize.maxRows); console.log("Description: "+ this.descFC.value); } //resizeToFitContent() and Reset() test contentFC = new FormControl(); @ViewChild('cfcAutosize') contentFCAutosize: CdkTextareaAutosize; resizeTextArea() { this.ngZone.onStable.pipe(take(ane)) .subscribe(() => this.contentFCAutosize.resizeToFitContent(true)); } resetTextAreaSize() { this.contentFCAutosize.reset(); } //Create a form personForm = this.formBuilder.group({ name: ['', Validators.required], address: ['', [Validators.required, Validators.maxLength(100)]] }); onFormSubmit() { this.personService.savePerson(this.personForm.value); } get name() { return this.personForm.become('name'); } get address() { render this.personForm.go('address'); } } person.ts
export interface Person { name: string; address: string; } person.service.ts
import { Injectable } from '@angular/cadre'; import { Person } from './person'; @Injectable({ providedIn: 'root' }) export class PersonService { savePerson(person: Person) { console.log(person); } } Template-Driven Form Example using Textarea
Notice the complete code to create textarea using template-driven form.
template-driven-grade.component.html
<h4>5. Person Template-Driven Class</h4> <form #personForm="ngForm" (ngSubmit)="onFormSubmit(personForm)"> <div> <mat-form-field> <input matInput placeholder="Proper name" name="name" required ngModel #name="ngModel" [errorStateMatcher]="esMatcher"> <mat-error *ngIf="name.hasError('required')"> Proper name is required. </mat-error> </mat-form-field> </div> <div> <mat-form-field> <textarea matInput placeholder="Address" name="address" required maxlength="100" ngModel #address="ngModel" cdkTextareaAutosize cdkAutosizeMinRows="two" cdkAutosizeMaxRows="four" [errorStateMatcher]="esMatcher"> </textarea> <mat-error *ngIf="accost.hasError('required')"> Comment is required. </mat-error> </mat-grade-field> </div> <div> <button mat-raised-button>Submit</button> </div> </class> template-driven-form.component.ts
import { Component, OnInit } from '@angular/core'; import { CustomErrorStateMatcher } from './custom-fault-land-matcher'; import { PersonService } from './person.service'; @Component({ selector: 'app-template-driven', templateUrl: './template-driven-form.component.html' }) export class TemplateDrivenFormComponent implements OnInit { constructor(private personService: PersonService) {} ngOnInit() { } esMatcher = new CustomErrorStateMatcher(); onFormSubmit(grade) { this.personService.savePerson(class.value); } } app.component.ts
import { Component } from '@angular/cadre'; @Component({ selector: 'app-root', template: ` <app-reactive></app-reactive> <app-template-driven></app-template-driven> ` }) export form AppComponent { } app.module.ts
import { BrowserModule } from '@athwart/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { NgModule } from '@angular/core'; import { FormsModule, ReactiveFormsModule } from '@athwart/forms'; import { MatFormFieldModule } from '@angular/fabric/course-field'; import { MatInputModule } from '@angular/material/input'; import { MatSelectModule } from '@athwart/fabric/select'; import { MatButtonModule } from '@angular/material/button'; import { ErrorStateMatcher } from '@athwart/material/core'; import { CustomErrorStateMatcher } from './custom-error-land-matcher'; import { AppComponent } from './app.component'; import { ReactiveFormComponent } from './reactive-form.component'; import { TemplateDrivenFormComponent } from './template-driven-class.component'; @NgModule({ declarations: [ AppComponent, ReactiveFormComponent, TemplateDrivenFormComponent ], imports: [ BrowserModule, BrowserAnimationsModule, FormsModule, ReactiveFormsModule, MatFormFieldModule, MatInputModule, MatSelectModule, MatButtonModule ], providers: [ // {provide: ErrorStateMatcher, useClass: CustomErrorStateMatcher} ], bootstrap: [AppComponent] }) export course AppModule { } styles.css
@import "~@angular/cloth/prebuilt-themes/indigo-pink.css";
Run Awarding
To run the application, find the steps.
one. Install Angular CLI using link.
2. Install Angular Material using link.
three. Download source code using download link given beneath on this page.
four. Use downloaded src in your Athwart CLI application.
v. Run ng serve using control prompt.
6. Access the URL http://localhost:4200
Find the print screen of the output.
References
Angular Material Input
CdkTextareaAutosize Directive
A Component Dev Kit (CDK) for Athwart
Download Source Code
Source: https://www.concretepage.com/angular-material/angular-material-textarea
Posted by: mcgeeancessitneve.blogspot.com

0 Response to "How To Make A Textarea Register Tab Angular 2"
Post a Comment