How to push to a FormArray([ ]) in angular 4

angular 6 formarray example
angular formarray push
formarray foreach
formarray valuechanges
formarray patchvalue
formarray of formgroups
ngfor formarray
remove formcontrol from formgroup

I have a reactive angular form that looks something like this.

 <form [formGroup]="myForm">
      <div *ngFor="let Repo of Repos;">
           <fieldset>
                <legend>{{Repo.name}}</legend>
                    <div class="checkbox checkbox-success">
                       <input
                            [id] = "Repo.id"
                            type="checkbox"   (change)="onChange(Repo.User,Repo.Commits,Repo.Requests,Repo.Contributors, Repo.Languages,Repo.Branches,Repo.Langs,$event.target.checked)">
                              <label [for] = "Repo.id">
                                 Select This Repository
                              </label>
                     </div>
            </fieldset>
       </div>
 </form>

Following is the typescript file:

export class AddUserComponent implements OnInit {
      githubUserResponse;
      githubReposResponse;
      myForm = new FormGroup({});
    ngOnInit(){
       this.myForm = new FormGroup({
            'userRepoData' : new FormGroup({
              'githubusers': new FormGroup({
                'username': new FormControl(null),
                'html_url': new FormControl(null),
                'name': new FormControl(null),
                'company': new FormControl(null),
                'location': new FormControl(null),
                'user_created_at': new FormControl(null),
                'user_updated_at': new FormControl(null),
                'public_repos': new FormControl(null),
                'public_gists': new FormControl(null),
                'githubrepos': new FormArray([]),
              }),
            }),
          });
    }
onChange(repo, commits, requests, contributors, branches, langs,  isChecked: boolean){
        if (!isChecked) {
         console.log('aayaa');
         (<FormArray>this.myForm.get('userRepoData.githubusers.githubrepos')).push(
           new FormGroup({
             'owner': new FormControl(repo.owner.login),
             'name': new FormControl(repo.name),
             'html_url': new FormControl(repo.html_url),
             'clone_url': new FormControl(repo.clone_url),
             'repo_created_at': new FormControl(repo.created_at),
             'repo_updated_at': new FormControl(repo.updated_at),
             'repo_pushed_at': new FormControl(repo.pushed_at),
             'public_repos': new FormControl(repo.public_repos),
             'no_of_commits': new FormControl(commits.length),
             'no_of_branches': new FormControl(branches.length),
             'no_of_pullrequests': new FormControl(requests.length),
             'no_of_contributors': new FormControl(contributors.length),
             'repobranches': new FormArray([]), //empty
             'repocommits': new FormArray([]), //empty
             'repocontributors': new FormArray([]), //empty
             'repolangs': new FormArray([]), //empty
             'repo_p_rs': new FormArray([]) //empty
           })
         );
         console.log(this.myForm.value);
  }
}

it can be seen in above FormGroup that the FormArrays : 1. repobranches 2. repocommits 3. repocontributors 4. repolang 5. repo_pr_s are empty. now i want to push some arrays within these nested FormArrays.

for example following is the array i want to push to 'repocontributors' :

[
                    {
                        "login": "Saurabh0606",
                        "id": 21239899,
                        "avatar_url": "https://avatars2.githubusercontent.com/u/21239899?v=4",
                        "gravatar_id": "",
                        "url": "https://api.github.com/users/Saurabh0606",
                        "html_url": "https://github.com/Saurabh0606",
                        "followers_url": "https://api.github.com/users/Saurabh0707/followers",
                        "following_url": "https://api.github.com/users/Saurabh0707/following{/other_user}",
                        "gists_url": "https://api.github.com/users/Saurabh0707/gists{/gist_id}",
                        "starred_url": "https://api.github.com/users/Saurabh0707/starred{/owner}{/repo}",
                        "subscriptions_url": "https://api.github.com/users/Saurabh0707/subscriptions",
                        "organizations_url": "https://api.github.com/users/Saurabh0707/orgs",
                        "repos_url": "https://api.github.com/users/Saurabh0707/repos",
                        "events_url": "https://api.github.com/users/Saurabh0707/events{/privacy}",
                        "received_events_url": "https://api.github.com/users/Saurabh0707/received_events",
                        "type": "User",
                        "site_admin": false,
                        "contributions": 2
                    }


{
                            "login": "Saurabh0707",
                            "id": 21239898,
                            "avatar_url": "https://avatars2.githubusercontent.com/u/21239898?v=4",
                            "gravatar_id": "",
                            "url": "https://api.github.com/users/Saurabh0707",
                            "html_url": "https://github.com/Saurabh0707",
                            "followers_url": "https://api.github.com/users/Saurabh0707/followers",
                            "following_url": "https://api.github.com/users/Saurabh0707/following{/other_user}",
                            "gists_url": "https://api.github.com/users/Saurabh0707/gists{/gist_id}",
                            "starred_url": "https://api.github.com/users/Saurabh0707/starred{/owner}{/repo}",
                            "subscriptions_url": "https://api.github.com/users/Saurabh0707/subscriptions",
                            "organizations_url": "https://api.github.com/users/Saurabh0707/orgs",
                            "repos_url": "https://api.github.com/users/Saurabh0707/repos",
                            "events_url": "https://api.github.com/users/Saurabh0707/events{/privacy}",
                            "received_events_url": "https://api.github.com/users/Saurabh0707/received_events",
                        "type": "User",
                        "site_admin": false,
                        "contributions": 2
                    }
                ]   

similarly others also.

how am i supposed to do this..? Help Required. Thanks In Advance.

As Imran mentioned I also recommend to use FormBuilder:

ngOnInit() {
  this.myForm = this._fb.group({
    userRepoData: this._fb.group({
      githubusers: this._fb.group({
        username: null,
        html_url: null,
        name: null,
        company: null,
        location: null,
        user_created_at: null,
        user_updated_at: null,
        public_repos: null,
        public_gists: null,
        githubrepos: this._fb.array([
          this._fb.group({
            owner: 'repo.owner.login',
            name: 'repo.name',
            html_url: 'repo.html_url',
            clone_url: 'repo.clone_url',
            repo_created_at: 'repo.created_at',
            repo_updated_at: 'repo.updated_at',
            repo_pushed_at: 'repo.pushed_at',
            repocontributors: this._fb.array([]), //empty
            repolangs: this._fb.array([]), //empty
          })
        ]),
      })
    })
  });
}

then just use push() method to push to your to array:

pushToArray() {
  const repocontributors = this.myForm.get('userRepoData.githubusers.githubrepos.0.repocontributors');
  (repocontributors as FormArray).push(this._fb.group({
    login: "Saurabh0606",
    id: 21239899,
    avatar_url: "https://avatars2.githubusercontent.com/u/21239899?v=4",
    gravatar_id: "",
    url: "https://api.github.com/users/Saurabh0606",
    html_url: "https://github.com/Saurabh0606",
    followers_url: "https://api.github.com/users/Saurabh0707/followers",
    following_url: "https://api.github.com/users/Saurabh0707/following{/other_user}",
    gists_url: "https://api.github.com/users/Saurabh0707/gists{/gist_id}",
    starred_url: "https://api.github.com/users/Saurabh0707/starred{/owner}{/repo}",
    subscriptions_url: "https://api.github.com/users/Saurabh0707/subscriptions",
    organizations_url: "https://api.github.com/users/Saurabh0707/orgs",
    repos_url: "https://api.github.com/users/Saurabh0707/repos",
    events_url: "https://api.github.com/users/Saurabh0707/events{/privacy}",
    received_events_url: "https://api.github.com/users/Saurabh0707/received_events",
    type: "User",
    site_admin: false,
    contributions: 2
  }));

  (repocontributors as FormArray).push(this._fb.group({
    login: "Saurabh0707",
    id: 21239898,
    avatar_url: "https://avatars2.githubusercontent.com/u/21239898?v=4",
    gravatar_id: "",
    url: "https://api.github.com/users/Saurabh0707",
    html_url: "https://github.com/Saurabh0707",
    followers_url: "https://api.github.com/users/Saurabh0707/followers",
    following_url: "https://api.github.com/users/Saurabh0707/following{/other_user}",
    gists_url: "https://api.github.com/users/Saurabh0707/gists{/gist_id}",
    starred_url: "https://api.github.com/users/Saurabh0707/starred{/owner}{/repo}",
    subscriptions_url: "https://api.github.com/users/Saurabh0707/subscriptions",
    organizations_url: "https://api.github.com/users/Saurabh0707/orgs",
    repos_url: "https://api.github.com/users/Saurabh0707/repos",
    events_url: "https://api.github.com/users/Saurabh0707/events{/privacy}",
    received_events_url: "https://api.github.com/users/Saurabh0707/received_events",
    type: "User",
    site_admin: false,
    contributions: 2
  }));
}

STACKBLITZ: https://stackblitz.com/edit/angular-ntx3sp?file=app%2Fapp.component.ts

Just press PUSH TO FORM ARRAY BUTTON.

This is how it looks before pushing:

and here after:

FormArray, const arr = new FormArray([ new FormControl(), new FormControl() ]); To change the controls in the array, use the push , insert , removeAt or clear methods in  Reactive-forms in Angular is very powerful to handle changes in value, check the statuses, and perform validations on a form-field in particular form because of supporting FormGroup, FormControl

Create your form builder first then set your existing array value in your repocontributors key just like

this.userForm = this._formBuilder.group({
   ...................
   ................
  'repocontributors': [yourArray]
});

Here is an example to build form builder in reactive form. Don't use on onChange() use submit please

Add/Push and Remove Form fields dynamically to FormArray with , Reactive-forms in Angular is very powerful to handle changes in value, check the statuses, Add/Push and Remove Form fields dynamically to FormArray with Reactive Forms in Angular. Kalpesh Shingala. Follow. Apr 1, 2019 · 4 min read. Angular FormArray Methods FormArray.at() Get the AbstractControl at the given index in the array. It is an index in the array to retrieve the control. FormArray.push() The push() function inserts a new AbstractControl at the end of the array. We have seen the push() method in our dynamic insert fields example. FormArray.insert()

githubrepos is an array, so get control for an element in that array. Then get control to repobranches (lets assume index 0), and push a new FormGroup with whatever values you want (assuming variable.login is a value here)

  var githubReposCtrl = (<FormArray>this.myForm.get('userRepoData.githubusers.githubrepos')).at(0);
  var repobranches = <FormArray>githubReposCtrl.get('repobranches');

  repobranches.push(new FormGroup(
    "login": new FormControl(variable.login);
    ...
  ))

Reactive Forms in Angular: Dynamically Creating Form Fields With , How do you dynamically add and remove form fields in Angularjs 7? The Angular FormArray example shows how to use the form array. The FormArray allows us to add controls dynamically to the reactive forms. In this example, we will take a very simple task of dynamically adding/removing skills to an employee form. Applies to: Angular 2, Angular 4, Angular 5, Angular 6, Angular 7, Angular 8. Angular 9.

Angular FormArray Example, Adding to the FormArray Dynamically. Now the interesting part is that we can to treat our FormArray just like a regular array and push new items  Propagating FormArray validators from child component to parent component in Angular 8 Hot Network Questions HNN-extension as a 2-colimit

Angular Reactive Forms: The Ultimate Guide to FormArray, The Angular Formarray example shows how to use the form array. Applies to: Angular 2, Angular 4, Angular 5, Angular 6, Angular 7, Angular 8. Since it is an array we can use the push method to add the new skill using  With FormArray you can therefore add new form fields or set of form fields declaratively. — Sorry to interrupt this program! 📺 If you're interested in learning Angular in a comprehensive and structured way, I highly recommend you check out ng-book. Learning from an organized and up-to-date resource like that should speed up your learning

Nested FormArrays in Angular ReactiveForms, In this article, I'd like to discuss this peculiar creation — a FormArray, exposed by Angular Reactive Forms. We'll learn when and how to use it,  content_copy const arr = new FormArray ([new FormControl ()], {updateOn: 'blur'}); Adding or removing controls from a form arraylink. To change the controls in the array, use the push, insert, removeAt or clear methods in FormArray itself. These methods ensure the controls are properly tracked in the form's hierarchy.

Comments
  • Please click PUSH TO FORM ARRAY button, which will trigger pushToArray() function, which will call FormArray's push() method. I updated my answer with 2 screenshots, before and after pushing to array.