如何以角度形式添加可选的ngModelGroup?

问题描述 投票:0回答:1

我在以角度形式添加可选的ngModelGroup时遇到了问题。我确实知道ngModelGroup在角形式中的用法,但是努力寻找一种使其成为可选方式的方法。

我尝试传递falsenullundefined仍然无法正常工作

请在下面找到代码示例和stackblitz链接

预期表单对象

{
"firstName": "",
"lastName": "",
"zip": "",
"street": "",
"city": ""}

感谢您的任何帮助

import { Component } from '@angular/core';
import { ControlContainer, NgForm } from '@angular/forms';

/*
  1. <fieldset ngModelGroup="address">  add address control object to form
  2. <fieldset [attr.ngModelGroup]="true ? 'address' : null">  not working
  3. <fieldset [ngModelGroup]="false ? 'address' : null">  

  so how to make ngModelGroup optional here ????
*/

@Component({
  selector: 'address',
  template: `
    <fieldset [ngModelGroup]="false ? 'address' : null">
      <div>
        <label>Zip:</label>
        <input type="text" name="zip" ngModel>
      </div>
      <div>
        <label>Street:</label>
        <input type="text" name="street" ngModel>
      </div>
      <div>
        <label>City:</label>
        <input type="text" name="city" ngModel>
      </div>
    </fieldset>
  `,
  viewProviders: [ { provide: ControlContainer, useExisting: NgForm } ]
})
export class AddressComponent  {}
javascript angular angular-forms angular-ngmodelgroup
1个回答
0
投票

您总是可以将表单值映射到适合您需要的对象...

getFlatFormValues(value: any) {
    const flatObject = {
      "firstName": value.firstName,
      "lastName": value.lastName,
    }

    if (value.address) {
        return {
          ...flatObject,
          ...value.address
        }
    }

    return flatObject;
  }

请参见此处的工作示例:https://stackblitz.com/edit/angular-ngmodelgroup-hgbro7

热门问题
推荐问题
最新问题