- Create an angular project with the below command.
ng new angular-material-forms-and-form-array
2. After successful creation of the angular app, change the file directory to project-name. “cd angular-material-forms-and-form-array”
Open the project in vs code using “code .” in terminal or open with vs code. Then run the project using “ng serve” in a terminal. Open project in chrome using
localhost:4200
3. Open the app component in vs code and remove the content which is created by angular CLI while creating the app.
For Adding angular material using the command"ng add @angular/material"
4. Select theme, Am selecting Indigo/Pink,
and click below items as “yes”
- Set up global Angular Material typography styles? Am selecting
y
- Set up browser animations for Angular Material? (Y/n) Select ‘y’.
5. Created Shared Module in the libs folder using “ng generate module shared”. And import , export material modules in “shared.module.ts”. And also add in the app.module.ts
6. Create audits component in the apps/component folder. And add audits component in router and path as audits
.
7. Add “ReactiveFormsModule”, and “Forms Module” in app.module.ts as below.
import { FormsModule, ReactiveFormsModule } from '@angular/forms';@NgModule({
declarations: [
AppComponent,
SignupComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
FormsModule,
ReactiveFormsModule,
SharedModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
8. Open “audits.component.ts”, then add “formbuilder ” as a dependency in the constructor. Create a form variable above the constructor.
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
public form:FormGroup;
constructor(private fb:FormBuilder) { }ngOnInit(): void { }
9. Create formInit method to initialize the form and call the method from either constructor or ngOnInit.
constructor(private fb:FormBuilder) {
this.formInit()
}ngOnInit(): void { }private formInit(){
}
10. And create form group using form builder and add controls in that same form. Form Controls like “firstName”, “second Name” , “email”, “username”, “password” and “mobile”.
private formInit(){
this.form = this.fb.group({
firstName: ['',[Validators.required]],
lastName: ['',[Validators.required]],
username: ['',[Validators.required, Validators.minLength(4), Validators.maxLength(25)]],
email: ['',[Validators.required]],
password: ['',[Validators.required, Validators.maxLength(8), Validators.maxLength(25)]],
});
}
11. After successfully following the above points. Add Html in signup.component.html related to the form step by step.
- Add div and form tag in Html file.
<div class=”container”>
<form class=”form shadow m-3 p-3" [formGroup]=”form” (ngSubmit)=”submitForm()”>
<h1>Sign Up Form</h1>
</form>
</div>
- Increase code by one form control and add validate message also.
<div class=”container”>
<form class=”form shadow m-3 p-3" [formGroup]=”form” (ngSubmit)=”submitForm()”>
<h1>Sign Up Form</h1>
<div class=”row mt-3">
<mat-form-field class=”col-md-6">
<mat-label>First Name</mat-label>
<input matInput formControlName=”firstName” placeholder=”Enter First Name”>
</mat-form-field>
</div>
</form>
</div>
- Add all the controls and form validation messages.
<div class="container">
<form class="form shadow m-3 p-3" [formGroup]="form" (ngSubmit)="submitForm()">
<h1>Sign Up Form</h1>
<div class="row mt-3">
<mat-form-field class="col-md-6">
<mat-label>First Name</mat-label>
<input matInput formControlName="firstName" placeholder="Enter First Name">
<mat-error *ngIf="this.form.controls.firstName.hasError('required')">
First Name is <strong>required</strong>
</mat-error>
</mat-form-field>
</div>
<div class="row mt-3">
<mat-form-field class="col-md-6">
<mat-label>Last Name</mat-label>
<input matInput formControlName="lastName" placeholder="Enter Last Name">
<mat-error *ngIf="this.form.controls.lastName.hasError('required')">
Last Name is <strong>required</strong>
</mat-error>
</mat-form-field>
</div>
<div class="row mt-3">
<mat-form-field class="col-md-6">
<mat-label>User Name</mat-label>
<input matInput formControlName="username" placeholder="Enter Username">
<mat-error *ngIf="this.form.controls.username.hasError('required')">
Username is <strong>required</strong>
</mat-error>
</mat-form-field>
</div>
<div class="row mt-3">
<mat-form-field class="col-md-6">
<mat-label>Email</mat-label>
<input matInput formControlName="email" placeholder="Enter Email">
<mat-error *ngIf="this.form.controls.email.hasError('required')">
Email <strong>required</strong>
</mat-error>
</mat-form-field>
</div>
<div class="row mt-3">
<mat-form-field class="col-md-6">
<mat-label>Password</mat-label>
<input type="password" matInput formControlName="password" placeholder="Enter Password">
<mat-error *ngIf="this.form.controls.password.hasError('required')">
Password is <strong>required</strong>
</mat-error>
</mat-form-field>
</div>
<div class="row mt-3">
<button type="submit" mat-raised-button color="primary" class="m-2" style="width: 100px;" [disabled]="!form.valid">Submit Form</button>
<button type="button" mat-raised-button color="warn" class="m-2" style="width: 100px;" (click)="form.reset()">Reset</button>
</div>
</form>
</div>
12. After successfully adding the HTML code and checking the changes in the browser. Add the submit method in signup.component.ts
public submitForm(){
console.log(this.form);
console.log(this.form.getRawValue())
}
13. Test the form by giving all the forms and clicking on submit. You can able to see the values in the console.
14. After that am adding hobbies as formArray inside formGroup like below.
private formInit(){
this.form = this.fb.group({
firstName: ['',[Validators.required]],
lastName: ['',[Validators.required]],
username: ['',[Validators.required, Validators.minLength(4), Validators.maxLength(25)]],
email: ['',[Validators.required]],
password: ['',[Validators.required, Validators.maxLength(8), Validators.maxLength(25)]],
hobbies: this.fb.array([
this.fb.group({
hobbie:['', [Validators.required]]
})
])
});
}
15. To get hobbies as FormArray to display hobbies, Am creating a get method and it will return hobbies as FormArray.
public get hobbies(){
return this.form.get('hobbies') as FormArray;
}
16. For adding hobbies am using “hobbies.push()” and remove “hobbies.removeAt(index) ”method. To remove hobbies, we need to pass the index as a parameter.
public addHobbie(){
const hobbie = this.fb.group({
hobbie:['', [Validators.required]]
})
this.hobbies.push(hobbie)
}public removeHobbie(index){
this.hobbies.removeAt(index)
}
17. Oops !!!, I forgot to add Html related to the hobbies array. To achieve that add the below lines of code.
<ng-container formArrayName="hobbies">
<ng-container *ngFor="let hobbie of hobbies.controls;let i = index">
<ng-container [formGroupName]="i">
<div class="row mt-3">
<mat-form-field class="col-md-6">
<input matInput placeholder="Enter hobbie #{{i}}" formControlName="hobbie">
</mat-form-field>
<button type="button" mat-raised-button color="primary" style="width: 10px;height: 34px; margin-left: 10px;margin-right: 10px;" class="ml-2 mr-2" (click)="addHobbie()"> + </button>
<button type="button" mat-raised-button color="warn" style="width: 10px;height: 34px; margin-left: 10px;margin-right: 10px;" class="mr-2 ml-2" *ngIf="i>0" (click)="removeHobbie(i)"> - </button>
</div>
</ng-container>
</ng-container>
</ng-container>
18. After successfully doing these steps, run the application by using ng serve and open the browser and copy localhost:4200 paste it into the browser address bar to see the changes.
19. Do you want to see the form values fill and submit the form, Go to the browser dev tools by right click, inspect and click on console,
Output Screens:
Screen #1: No Errors
Screen #2: All Errors
Screen #3: Form with Values
Screen #4: Multiple hobbies
Screen #5: Removing Hobbie “Reading Article”.
Screen #6: Console the Form Details After submit.
Source CodeFront End:
GitHub:
mryenagandula/angular-material-forms-and-form-arrayStack Blitz:
https://stackblitz.com/edit/angular-material-forms-and-form-array
Thanks for reading my article, Please share your feedback, claps, and comments. In that way, it will be helped me to improve my articles in the future. Please share my story with your near and dear, Also follow and subscribe to the medium.