只需要 JSON 嵌套 FormArray 中没有其键的值 - Angular

Just need JSON value without its key in nested FormArray - Angular

我有一个 Angular 表单,它从用户那里获取输入并将其转换为 JSON 对象。

我需要这样的输出:

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

我需要没有键的 JSON 值,在另一个 JSON 列表中

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

我正在使用 Reactive 表单并创建了一个嵌套的 FormArray,通过这样做,我能够得到这样的输出:

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

但是,如何使用上面提到的值(没有键)创建另一个嵌套的 FormArray?

我的component.ts

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

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

首先定义数组

const mobileNumbers = [];

然后使用嵌套循环从原始对象中获取手机号码。在我的示例中,它被命名为 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);

这样试试:

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')
  }

您需要像这样修改您的代码

首先,如果你想在 formgroup 中创建数组

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

然后你必须像这样循环手机号码并将其传递给formarray。 它将创建数组列表

// 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>

您只需要为每个手机号码创建 control,而不是创建 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('')
    ];
  }

查看我在此处创建的示例:https://stackblitz.com/edit/angular-reactive-forms-control

你可以试试:

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)])
                     ]
        });
    }

我不确定它是否对你有帮助。你可以从上面的代码中得到启发。

我想到了这样做,

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(' ') ;
 }

这样,用户可以输入多个手机号码,space分隔,拆分操作returns作为一个数组。

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

我可以得到这样的输出。