如何在FormGroup中添加动态formControl

时间:2018-02-17 15:13:02

标签: javascript angular forms

这是我以静态方式创建的。我正在使用Angular 4。

   this.contactForm = this.fb.group({

  firstname: ['', Validators.required],
  lastname: ['', Validators.required],
  zipCode: ['', Validators.required],
  hobbies: this.fb.group({
    hobbies0: ['', Validators.required],
    hobbies1: ['', Validators.required],
    hobbies2: ['', Validators.required],
    hobbies3: ['', Validators.required],
    hobbies4: ['', Validators.required],
    hobbies5: ['', Validators.required]
  }),// want to create these controls using for loop.


})

以HTML格式

 <form [formGroup]="contactForm " autocomplete="off" (ngSubmit)="onSubmit()">
         <input type="text" formControlName="firstname">
         <input type="text" formControlName="lastname">
         <input type="text" formControlName="zipCode">
         <div formGroupName="hobbies">
            <input type="text" formControlName="hobbies0">
            <input type="text" formControlName="hobbies1">
            <input type="text" formControlName="hobbies2">
            <input type="text" formControlName="hobbies3">
            <input type="text" formControlName="hobbies4">
            <input type="text" formControlName="hobbies5">
         </div>//want to iterate through ngFor
 </form>

所以,我刚才开始知道一种以动态方式创建此类内容的方法,方法是在html中使用*ngFor,在typescript中创建动态controls

1 个答案:

答案 0 :(得分:0)

例如,您可以执行以下操作:

<强> component.ts

  public hobbiesArr = ['hobbies0', 'hobbies1', 'hobbies2', 'hobbies3', 'hobbies4'];

  ngOnInit() {
    const hobbiesGroup = {}
    this.hobbiesArr.forEach(hobby => {
      hobbiesGroup[hobby] = new FormControl('', Validators.required);
    })

    this.contactForm = this.fb.group({
      firstname: ['', Validators.required],
      lastname: ['', Validators.required],
      zipCode: ['', Validators.required],
      hobbies: new FormGroup(hobbiesGroup)
    })

  }

<强> component.html

     <form [formGroup]="contactForm" autocomplete="off" (ngSubmit)="onSubmit()">
      <input type="text" placeholder="firstname" formControlName="firstname">
      <input type="text" placeholder="lastname" formControlName="lastname">
      <input type="text" placeholder="zipCode" formControlName="zipCode">

      <div formGroupName="hobbies">
        <input *ngFor="let hobby of hobbiesArr" [placeholder]="hobby" type="text" [formControlName]="hobby">
      </div>

      <button type="submit">Submit</button>
      
     </form>