【问题标题】:Just need JSON value without its key in nested FormArray - Angular只需要 JSON 值而没有嵌套 FormArray 中的键 - Angular
【发布时间】:2018-07-18 05:02:02
【问题描述】:

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

我需要这样的输出:

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

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

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

我正在使用响应式表单并创建了一个嵌套的 FormArray,通过这样做,我可以获得如下输出:

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

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

我的组件.ts

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

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

【问题讨论】:

  • 为什么需要手机":["123","456","789"] ?
  • 拥有手机号码列表
  • 它只是一种格式吗?为什么你的手机号只有9位?
  • 3位数字只是一个例子,一个占位符而不是让它变大
  • 你可以有一个 FormGroups 的 FormArray 或一个 FormControls 的 FormArray。 .html 中有几个不同之处。你可以在我的回答中看到一个例子stackoverflow.com/questions/51136985/…

标签: json angular angular5 angular6


【解决方案1】:

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

首先如果你想在表单组中创建数组

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>

【讨论】:

  • 感谢您的想法,我想从表单中获取手机号码作为用户输入。我该怎么做?
【解决方案2】:

先定义数组

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

【讨论】:

    【解决方案3】:

    试试这样:

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

    【讨论】:

    • 感谢您的建议,如何在此处包含用户输入?
    【解决方案4】:

    您只需为每个手机号码创建controls,而不是创建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

    【讨论】:

    • 谢谢!如果您告诉我如何从用户那里获取输入并列出列表,那就太好了。
    【解决方案5】:

    你可以试试:

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

    我不确定它是否会帮助你。你可以从上面的代码中得到一个想法。

    【讨论】:

      【解决方案6】:

      我想过这样做,

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

      这样,用户可以输入多个手机号码,用空格隔开,拆分操作返回一个数组。

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

      我可以得到这样的输出。

      【讨论】:

        猜你喜欢
        • 2019-02-04
        • 2021-09-16
        • 2014-12-03
        • 1970-01-01
        • 2018-03-20
        • 2020-09-14
        • 1970-01-01
        • 2018-08-14
        • 2020-04-24
        相关资源
        最近更新 更多