Angular2表单ControlGroup,其中包含未定义的Control数

前端之家收集整理的这篇文章主要介绍了Angular2表单ControlGroup,其中包含未定义的Control数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何使用Angular2管理一个包含未定义字段数的表单?

在我的情况下,我需要创建一个用户可以添加删除一些文件块的地方.它就像一个地址簿,用户可以在其中添加一个或十个地址.每个地址都有一些字段,如街道,街道号码等.

我看起来像这样:

let address = fb.group({
        street: fb.control(null,Validators.required),streetNumber fb.control(null,Validators.required)
    });

this.userForm = fb.group({
        name: fb.control(null,firstName: fb.control(null,address: fb.group({
            1: address
            })
        });

我真的不知道如何在模板中管理它.

我试着在模板中写一些这样的东西,但很明显,它不起作用……

<form [ngFormModel]="userForm">
<input type="text" ngControl="name" #name="ngForm"/>
<input type="text" ngControl="firstName" #firstName="ngForm"/>

<div *ngFor="#address of userForm.controls['address'].controls">
    <input type="text" ngControl="street" #street="ngForm"/>
    <input type="text" ngControl="streetNumber" #streetNumber="ngForm"/>
</div>

编辑

我做了一个Plunker以获得更好的解释http://plnkr.co/edit/ffYe1479WnxYOQrbxwLF?p=preview

我为你实现了它,见 Plunker或更好,Plunker -@waldo
import {Component} from 'angular2/core';
import {
  FORM_DIRECTIVES,FormBuilder,ControlGroup,ControlArray,Validators,NgForm,Control,AbstractControl
} from 'angular2/common';

@Component({
  selector: 'my-app',template: `
    <form [ngFormModel]="userForm" *ngIf="userForm">
      <p><label><input id="date" type="text" ngControl="name" #name="ngForm"/> Name</label></p>

      <p><label><input id="date" type="text" ngControl="firstName" #firstName="ngForm"/> FirstName</label></p>

      <h3>Add address</h3>
        <ul ngControlGroup="addresses">

        <li *ngFor="#ctrl of objToArray(userForm.find('addresses').controls); #i = index" 
        ngControlGroup="{{ctrl}}">
           {{ctrl}}:
          <input ngControl="street" placeholder="Street">
          <input ngControl="streetNumber"  placeholder="StreetNumber"> 
        </li>
      </ul>

    <div (click)="addAddress()" style="cursor: pointer"> Add Another Address</div>

    </form>

    `,directives: [FORM_DIRECTIVES]
})
export class AppComponent {
  userForm: ControlGroup;

  constructor(private fb: FormBuilder) {

    this.userForm = fb.group({
      name: fb.control(null,addresses: fb.group({
        address1: fb.group({
          street: fb.control(null,streetNumber: fb.control(null,Validators.required)
        })
      })
    });

    console.log(this.userForm);

  }

  objToArray(o){
    return Object.keys(o);
  }

  addAddress() {
    let addressField = this.fb.group({
      street: this.fb.control(null,streetNumber: this.fb.control(null,Validators.required)
    });

    (<ControlGroup>this.userForm.find('addresses')).addControl(
      'address' + (Object.keys((<ControlGroup>this.userForm.find('addresses')).controls).length + 1),addressField);
  }
}
原文链接:https://www.f2er.com/angularjs/143325.html

猜你在找的Angularjs相关文章