Open In App

Angular forms FormArrayName Directive

Last Updated : 04 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we are going to see what is Style in Angular 10 and how to use it.

The FormArrayName is used to sync a nested FormArray to a DOM element.

Syntax:

<div formArrayName="arrayName">

NgModule: Module used by FormArrayName is:

  • ReactiveFormsModule

 

Selectors:

  • [FormArrayName]

Approach: 

  • Create the Angular app to be used
  • In app.component.ts make an array that takes the value from the form
  • In app.component.html make a form and send the value to the array to the submission.
  • Serve the angular app using ng serve to see the output.

Example 1:

app.component.ts




import { Component, Inject } from '@angular/core';
import { FormGroup, FormControl, FormArray } from '@angular/forms'
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    form = new FormGroup({
        courses: new FormArray([]),
    });
  
    get courses(): FormArray {
        return this.form.get('courses') as FormArray;
    }
  
    addCourse() {
        this.courses.push(new FormControl());
    }
  
    onSubmit() {
        console.log(this.courses.value);
    }
  
}


app.component.html




<br>
<form [formGroup]="form" (ngSubmit)="onSubmit()">
    <div formArrayName="courses">
  
        <div *ngFor="let course of courses.controls; index as i">
            <input [formControlName]="i" placeholder="Course">
        </div>
    </div>
    <br>
    <button>Submit</button>
    <br><br>
</form>
  
<button (click)="addCourse()">Add Course</button>


Output:

Reference: https://angular.io/api/forms/FormArrayName



Next Article

Similar Reads