将角动态表转换为角度2反应形式

时间:2016-09-08 16:56:49

标签: arrays angular angular2-forms

我正在尝试将a working example of an angular dynamic table转换为angular2反应形式。我想以角度2形式实现相同的功能:

  • 提交3个新输入值,这些输入值将添加到表格

  • 新值,每次都会添加到formArray

我认为我很接近,但我认为我在编写使其失败的initData函数时必定存在一些问题。我是否正确地认为我可以将新的数据条目作为initData函数的参数传递以更新formArray?

任何帮助或方向表示赞赏! 感谢

live Plunk here

app.component.html     

  <div formArrayName="personalDetails ">
  <input [(ngModel)]="newData.fname" type="text" formControlName="fname">
  <input [(ngModel)]="newData.lname" type="text" formControlName="lname">
  <input [(ngModel)]="newData.email" type="text" formControlName="email">
  </div>
  <button (click)=addNew()>Add</button>

  <table >
    <thead>
      <tr>
        <th>First Name</th>
        <th>Last Name</th>
         <th>Email</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let personalDetail of myForm.controls.personalDetails.controls" >
         <td>{{personalDetail.fname}}</td>
         <td>{{personalDetail.lname}}</td>
         <td>{{personalDetail.email}}</td>
      </tr>
    </tbody>
  </table>
</form>

app.component.ts

        export class AppComponent implements OnInit {
         public myForm: FormGroup;
         public newData: Data;

            constructor(private _fb: FormBuilder) { }

            ngOnInit() {
                this.newData = new Data();

                this.myForm = this._fb.group({
                    personalDetails : this._fb.array([
                        this.initData(entryObj),
                    ])
                });
            }

            // create the new formGroup to push to the personalDetails array
            initData(entryObj:any) {
                return this._fb.group({
                    fname: [entryObj.fname],
                    lname: [entryObj.lname],
                    email: [entryObj.email]
                });
            }

            // add new set of Data
            // the new entry variable will be the argument for initData
            addNew() {
                if (this.newData) {
                    var entry = {
                        'fname': this.newData.fname,
                        'lname': this.newData.lname,
                        'email': this.newData.email
                    };

                    // add to the form controls
                    const control = <FormArray>this.myForm.controls['personalDetails '];
                    control.push(this.initData(entry));
                }
            }
        } 
    export class Data {
      public fname: string;
      public lname: string;
      public email: string;
}

就方法而言,我试图从the scotch example中引用,这里的主要区别在于新的formGroup值是在增加表单数组的同时提交的。

0 个答案:

没有答案