在角度2中添加动态反应形式组

时间:2016-11-15 08:00:18

标签: javascript angularjs forms typescript

我有一个具有回复功能的留言服务。此回复功能特定于用户想要回复的消息组。我需要在typescript和模板中动态添加表单验证,在构造函数中使用表单生成器进行某种循环,然后如何将mailData.length值传递回构造函数?  我在网上尝试了角度教程和其他一些,但没有运气。

// mail.component.ts 
  constructor(fb: FormBuilder) {
    this.MailForm = fb.group({
      "content": [null, Validators.compose([Validators.required, /*other validation*/])]
    });
  }
  sendMail(mail:any) {
  // Send mail
  }

然后在mail.html

<div *ngFor="let item of mailData; let i = index">
    // display original messages here

    // reply section 
    <div id="{{i}}">
        <form [formGroup]="i.MailForm">
            <textarea class="mailContainerTextArea" 
            [formControl]="i.MailForm.controls['content']">
            </textarea>
            <!-- Reply button -->
            <button class="mailReply" (click)="sendMail(i.MailForm.value)" [disabled]="!MailForm.valid">Send</button>
        </form>
    </div>
</div>

1 个答案:

答案 0 :(得分:0)

经过大量的搜索和游戏后,我终于得到了它,在线教程只为点击事件添加了元素,而不是基于现有阵列数据创建的表格组。答案基于Scotch-io-nestedForms

的部分
    //component 
    import { FormBuilder, FormGroup, FormArray, Validators } from "@angular/forms";
    //other imports FormArray is the important one 

export class SomeComponent{
    public MailFormArray:FormGroup;
    cnstructor(private fb: FormBuilder) {
        this.MailFormArray = fb.group({
            "reply": fb.array([
                this.createForms(),
            ])
        });
      }
      // generate the array content
      createForms() {
            return this.fb.group({
              "content": [null, Validators.compose([Validators.required, Validators.pattern('[a-z]')])]
            });
      }
      // create dynamic fields by calling this function after json data loaded, and pass in the json data length 
      addForms(jsonLength) {
          for(let i = 0; i < jsonLength; i++){
            const control = <FormArray>this.MailFormArray.controls['reply'];
            control.push(this.createForms());
          }
      }
     // replyForm
     replyForm(theReply) {
       console.log(JSON.stringify(theReply));
     }
}

然后在模板中

<form [formGroup]="MailFormArray">
    <div formArrayName="reply">
        <div *ngFor="let key of jsonData; let j = index;">
            <div [formGroupName]="j">
                <div *ngFor="let item of key;">
                    <textarea  maxlength="255" formControlName="content"></textarea>
                    <button (click)="replyForm(MailFormArray.controls.reply.controls[j].value)">Send</button>
                </div>
            </div>
        </div>
    </div>
</form>