有没有办法在angular2中使用ngForm获取数组值

时间:2016-04-28 07:58:44

标签: typescript angular angular2-forms

例如,我写了一个这样的组件。

@Component({
    selector: 'home',
    template:
        `
        <form (ngSubmit)="onSubmit(f)" #f="ngForm">
            <input type="text" ngControl="people">
            <input type="text" ngControl="people">
            <input type="submit">
        </form>
    `
})
export class Home {
    onSubmit(f) {
        console.log(f.value);
    }
}

当我为每个表单输入“tom”和“bob”并单击“Submit”按钮时,控制台说:

Object {people: "bob"}

我的期望是:

Object {people: ["tom", "bob"]}

是否可以使用ngForm获取数组值?

2 个答案:

答案 0 :(得分:1)

这是一个使用ControlArray符合我要求的示例。

import {Component} from 'angular2/core';
import {FORM_DIRECTIVES, Control, FORM_PROVIDERS, FormBuilder} from 'angular2/common';

@Component({
        selector: 'home',
        template:
            `
            <form [ngFormModel]="sampleForm" (ngSubmit)="onSubmit(sampleForm)">
                <div ngControlGroup="people">
                    <div *ngFor="let item of sampleForm.controls.people.controls; let i = index">
                        <input type="text" ngControl='{{ i }}'>
                        <button (click)="delPerson(i)">Del</button>
                    </div>
                </div>
                <button (click)="addPerson($event)">Add</button>
                <input type="submit">
            </form>
        `,
        providers: [FORM_PROVIDERS]
    })
export class Home {

    sampleForm: any;

    constructor(private builder: FormBuilder) {
        this.sampleForm = this.builder.group({
            people: this.builder.array([new Control()])
        });
    }

    addPerson(event) {
        event.preventDefault();
        this.sampleForm.controls.people.push(new Control());
    }

    delPerson(i: number) {
        this.sampleForm.controls.people.removeAt(i);
    }

    onSubmit(f) {
        console.log(f.value);
    }
}

这对我来说效果很好,但我认为这部分(let item of sampleForm.controls.people.controls)并不美观,我也不知道这是对ngForm的一个很好的用法。

答案 1 :(得分:0)

我会为您的员工创建符合ngModel / control的子组件:

const PEOPLE_VALUE_ACCESSOR = new Provider(
  NG_VALUE_ACCESSOR, {useExisting: forwardRef(() => PeopleComponent), multi: true});

@Component({
  selector: 'people',
  template: `
    <div>
      Person 1 : <input [(ngModel)]="person1" (ngModelChange)="doOnChange()"/><br/>
      Person 2 : <input [(ngModel)]="person2" (ngModelChange)="doOnChange()"/>
    <div>
  `,
  providers: [ PEOPLE_VALUE_ACCESSOR ]
})
export class PeopleComponent implements ControlValueAccessor {
  onChange = (_) => {};
  onTouched = () => {};

  writeValue(value:any):void {
    if (value!=null) {
      this.person1 = value[0];
      this.person2 = value[1];
    }
  }

  doOnChange(elt) {
    this.onChange([ this.person1, this.person2 ]);
  }

  registerOnChange(fn: (_: any) => void): void { this.onChange = fn; }
  registerOnTouched(fn: () => void): void { this.onTouched = fn; }
}

你可以这样使用它:

<form>
  <div>
    <people #people="ngForm" ngControl="people"></people>
    people : {{people.value}}
  </div>
</form>

在相关控件(此处people.value)内,您将拥有一个数组。

请参阅此plunkr:https://plnkr.co/edit/ix8unZ58hvqojjAic0E3?p=preview