从主对象算起的嵌套反应形式

Nested Reactive Form to count from main Object

我想从数据创建一个nested form

我的实际数据是:

mainObject = {
  adminname: 'Saqib',
  adminemail: 'email@example.com',
  users: [
    { user_type: 'Adult', count: 3 },
    { user_type: 'Child', count: 1 },
    { user_type: 'infant', count: 0 },
  ],
};

我想在用户数组中显示这些计数的嵌套形式。比如应该有 3 个成人表格,1 个儿童表格,没有婴儿表格,因为婴儿计数为 0。这些计数可以更改,例如可能有 0 个儿童和 1 个婴儿。

.html

<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
  <input formControlName="name" placeholder="Enter Admin Name" />
  <br />
  <input formControlName="admin_email" placeholder="Enter Admin Email" />

  <div formArrayName="users">
    <div *ngFor="let pro of myForm.get('users').controls; let i = index">
      <br />
      <div [formGroupName]="i" style="border: 1px solid; padding: 10px">
        <div>User Type: {{ pro.value.user_type }}</div>
        User Name:<br />
        <input type="text" formControlName="user_name" /> <br />

        Email:<br />
        <input type="text" formControlName="user_email" />
      </div>
    </div>
  </div>
  
  <p>
    <button type="submit">Submit</button>
  </p>
</form>

.ts

myForm: FormGroup;

  mainObject = {
    adminname: 'Saqib',
    adminemail: 'email@example.com',
    users: [
      { user_type: 'Adult', count: 3 },
      { user_type: 'Child', count: 1 },
      { user_type: 'infant', count: 0 },
    ],
  };
  // I want to Show forms according to this users count with their Type:
  // according to this data there should be 3 adult forms, 1 hchild form and no infant Form.

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.formInit();
  }

  formInit() {
    this.myForm = this.fb.group({
      name: '',
      admin_email: '',
      users: this.fb.array(
        this.mainObject.users.map((e) => this.newUsers(e.user_type, e.count))
      ),
    });
  }

  get users(): FormArray {
    return this.myForm.get('users') as FormArray;
  }

  newUsers(t, c): FormGroup {
    console.log(t, c);
    return this.fb.group({
      user_type: t,
      user_name: '',
      user_email: '',
    });
  }

  onSubmit() {
    console.log(this.myForm.value);
  }

为了更好地理解,我创建了示例 Stackblitz:

Example Stackblitz

或许你可以实现如下概念:

概念:

  1. 创建一个包含按键分组的字典:user_type 和值:一个包含基于 count.[=17= 创建的(多个)对象的数组]

  2. 从结果 1 中获取值,执行展平嵌套数组并将这些对象添加到数组中。

toFormUsers(users: any[]): any[] {
  // Generate array by user_type   
  let userTypeGroup = users.reduce((accumulator, current) => {
    accumulator[current.user_type] = accumulator[current.user_type] || [];

    for (let i = 0; i < current.count; i++)
      accumulator[current.user_type].push({ user_type: current.user_type });

    return accumulator;
  }, {});

   // Flatten array of array for userTypeGroup
  return [].concat(
    ...Object.keys(userTypeGroup).map((x) => userTypeGroup[x])
  );
}

并通过传递 mainObject.users 修改您的 FormGroup 以应用上述方法。

this.myForm = this.fb.group({
  name: '',
  admin_email: '',
  users: this.fb.array(
    this.toFormUsers(this.mainObject.users).map((e) => this.newUsers(e.user_type, e.count))
  ),
});

Sample Demo on StackBlitz

mainObject:

的用户数组中创建嵌套计数数组

.ts

ngOnInit() {
    this.formInit();
  }

  formInit() {
    this.myForm = this.fb.group({
      name: '',
      admin_email: '',
      users: this.fb.array([]),
    });

    this.mainObject.users.map((e) => {
      if (e.count > 0) {
        for (let i = 0; i < e.count; i++) {
          this.addUser(e.user_type);
        }
      }
    });
  }

  addUser(t) {
    const userArray = <FormArray>this.myForm.controls['users'];
    const newUser = this.initUser(t);
    userArray.push(newUser);
  }

  initUser(t) {
    return this.fb.group({
      user_type: t,
      user_name: '',
      user_email: '',
    });
  }

  get users(): FormArray {
    return this.myForm.get('users') as FormArray;
  }

  newUsers(t, c): FormGroup {
    console.log(t, c);
    return this.fb.group({
      user_type: t,
      user_name: '',
      user_email: '',
    });
  }