Angular Material Forms -Adding Form Array in Forms(Learn it in 19 Steps)
- 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
shared.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](twitter.com/angular/forms "Twitter profile for @angular/forms")';
[@NgModule](twitter.com/NgModule "Twitter profile for @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](twitter.com/angular/forms "Twitter profile for @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.
<form class=”form shadow m-3 p-3" [formGroup]=”form” (ngSubmit)=”submitForm()”>
Sign Up Form
- Increase code by one form control and add validate message also.
Sign Up Form
<mat-form-field class=”col-md-6">
First Name
- Add all the controls and form validation messages.
Sign Up Form
First Name
First Name is required
Last Name
Last Name is required
User Name
Username is required
Email
Email required
Password
Password is required
Submit Form
Reset
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.
+
-
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 Code
Front End:
GitHub: mryenagandula/angular-material-forms-and-form-array
Stack Blitz: stackblitz.com/edit/angular-material-forms-..
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.