代码之家  ›  专栏  ›  技术社区  ›  Ricardo Saracino

使用Angular FormControls时,将JavaScript对象从平面对象规范化为嵌套对象

  •  0
  • Ricardo Saracino  · 技术社区  · 7 年前

    这个问题源于使用从ngModel重构的角度表单控件

    this.form.addControl('Contact.Attributes.firstname', new FormControl('', Validators.required));
    

    模型重构

    [(ngModel)]="object.Contact.Attributes.firstname">
    

    所以我有一个“平面”对象,我需要把它变成一个嵌套值的标准化对象。。有没有一种聪明的方法不用编写自己的解析器就可以做到这一点?

    把这个变成(此窗体值)

    {
     Contact.Attributes.firstname: "", 
     Contact.Attributes.middlename: "", 
     Contact.Attributes.lastname: ""
    }
    

    Contact: {
      Attributes: {
        firstname: "",
        middlename: "",
        lastname: "",
    }
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Uladzislau Vavilau    7 年前

    你能试试吗,

    const unflatten = require('flat').unflatten;
    
    unflatten({
        'three.levels.deep': 42,
        'three.levels': {
            nested: true
        }
    })
    

    结果:

    // {
    //     three: {
    //         levels: {
    //             deep: 42,
    //             nested: true
    //         }
    //     }
    // }
    

    https://github.com/hughsk/flat

        2
  •  1
  •   Community Mohan Dere    6 年前

    对于反应形式

    /**
     * Add a control to this group.
     *
     * This method also updates the value and validity of the control.
     *
     * @param name The control name to add to the collection
     * @param control Provides the control for the given name
     */
    addControl(name: string, control: AbstractControl): void;
    

    这意味着您可以将FormControl或FormGroup对象传递给addControl方法,因为这两个对象都是AbstractControl的实例。更何况你的这个表格是FormGroup的实例

    /** Component */
    this.form.addControl('Contact', new FormGroup({
        Attributes: new FormGroup({
          firstName: new FormControl('', Validators.required),
          lastName: new FormControl('', Validators.required)
        })
    }));
    
    /** Template bindings */
    <form [formGroup]="form">
       <div [formGroup]="form.controls.Contact.controls.Attributes">
        <input formControlName="firstName" id="firstName" type="text" class="form-control" />
        <input formControlName="lastName" id="lastName" type="text" class="form-control" />
      </div>
    </form>
    

    对于基于模板的表单

    把你的意见用 ngModelGroup 指令

    <div ngModelGroup="Contact" >
      <div ngModelGroup="Attributes" >
        <input [(ngModel)]="object.firstname" name="firstname" id="firstname" class="form-control"/>
      </div>
    </div>
    

    Here 你可以用活生生的例子。创建-事件组件具有ngModelGroup位置。

    推荐文章