0

I have an Angular form which gets input from a user and converts it into a JSON object.

I need an output like this:

{"Name":"sam","age":"21","Friends":[{"Name":"bob","mobile":["123","456","789"]}]}

I need the JSON values without the key, inside another JSON list

"mobile":["123","456","789"] 

I am using Reactive forms and created a nested FormArray, by doing so, I am able to get an output like this:

{"Name":"sam","age":"21","Friends":[{"Name":"bob","mobile":"123"}]}

But, how do I create another nested FormArray just with the values(without key) as mentioned above?

My component.ts

this.peopleList = this._fb.group({
  Name : '',
  age : '',
  Friends: this._fb.array([this.CreateFriendList()])
});

CreateFriendList(): FormGroup {
   return this._fb.group({
      Name: '',
      mobile : '',
   });
 }
5
  • why you need mobile":["123","456","789"] ? Commented Jul 18, 2018 at 5:03
  • To have a list of mobile numbers Commented Jul 18, 2018 at 5:04
  • is it a format only ? Why your mobile no has 9 digit only ? Commented Jul 18, 2018 at 5:05
  • The 3 digit number is just an example, a placeholder instead of making it big Commented Jul 18, 2018 at 5:07
  • You can have an FormArray of FormGroups or a FormArray of FormControls. There are several diferences in the .html. You can see an example in my answer in stackoverflow.com/questions/51136985/… Commented Jul 18, 2018 at 6:27

6 Answers 6

1

You need modify your code like this

First if you want to create array inside formgroup

CreateFriendList(): FormGroup {
   return this._fb.group({
      Name: '',
      mobile : new FormArray(mobile),
   });
 }

Then you have to loop the mobile number like this and pass that to formarray. It will create list of array

// mobile number
   mobile=[1231323123,14231323,1231434134];
   const mobile= this.mobile.map(c => new FormControl(c));

Html

<form [formGroup]="form" (ngSubmit)="submit()">
  <label formArrayName="mobile" *ngFor="let order of form.controls.mobile.contols; let i = index">
    <input type="text" [formControlName]="i">
    {{mobile[i] }}
  </label>

</form>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your idea, I want to get the mobile number from the form as a user input. How do I do that?
0

First define the array

const mobileNumbers = [];

Then use nested loops to get the mobile numbers out of the original object. In my example it‘s named list.

// get each main element
list.forEach( element => { 

    // get the mobile number of each friend
    element.Friends.forEach( friend => { 
        mobileNumbers.push(friend.mobile);
    });    

});

// check the outcome 
console.log(mobileNumbers);

Comments

0

try like this:

CreateFriendList(): FormGroup {
    return this.fb.group({
      Name: '',
      mobile: this.fb.array([]),
    });
  }



getFriendsData() {
        return this.peopleList.get('Friends') as FormArray;
    }

  getFriendsNumber(): Array<any>{
    return this.getFriendsData().get('mobile').value
  }

  updateMobileNumber(){
    this.getFriendsNumber().push('122')
  }

1 Comment

Thank you for your suggestion, How do I include the user input here?
0

You just need to create controls for each mobile number instead of creating group

createFriendList(): FormGroup {
    return this._fb.group({
        name: '',
        mobile : this._fb.array(this.createFriendsMobileList()),
    });
  }

  createFriendsMobileList() {
    return [
      this._fb.control(''),
      this._fb.control(''),
      this._fb.control('')
    ];
  }

See this example that I created here: https://stackblitz.com/edit/angular-reactive-forms-control

1 Comment

Thank you!. It would be nice if you tell me how to get an input from a user and make the list.
0

You can try it:

import { FormBuilder, FormGroup, Validators, NgForm } from '@angular/forms';
import { Component } from '@angular/core';

@Component({
    selector: 'my-app',
    templateUrl: './component.html',
    styleUrls: ['./component.css']
})

export class LoginComponent implements OnInit {
    private loginForm: any;

    constructor(
        private formBuilder: FormBuilder
    ) {
        this.loginForm = this.formBuilder.group({
            name:      ['', Validators.compose([Validators.required])],
            age:       ['', Validators.compose([Validators.required])],
            friends:   [
                       this.formBuilder.group({
                            fName: ['', Validators.compose([Validators.required])],
                            mobiles: [[], Validators.compose([Validators.required])],
                        }),
                        Validators.compose([Validators.required, 
                                            Validators.minLength(1)])
                     ]
        });
    }

I am not sure that it will help you or not. You can take an idea from the above code.

Comments

0

I thought of doing this way,

this.peopleList = this._fb.group({
  Name : '',
  age : '',
  Friends: this._fb.array([this.CreateFriendList()])
});

CreateFriendList(): FormGroup {
   return this._fb.group({
      Name: '',
      mobile : '',
   });
 }

   const mobileList = this.peopleList.get('Friends') as FormArray;

for (let i = 0; i < mobileLists.length; i++) {
   this.peopleList.value.Friends[i].mobile = this.peopleList.value.Friends[i].mobile.split(' ') ;
 }

This way, User can enter multiple mobile numbers with space separated and the split operation returns as an array.

"mobile":["123","456","789"] 

I can get the output like this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.