在angular 2中添加动态响应式表单组

add dynamic reactive form groups in angular 2

本文关键字:响应 表单 动态 添加 angular      更新时间:2023-09-26

我有一个具有回复功能的消息服务。此回复功能特定于用户想要回复的消息组。我需要在typescript和模板中动态添加表单验证,在构造函数中围绕表单构建器进行某种循环,然后我如何传递mailData。长度值返回构造函数?我已经尝试了angular教程和其他一些在线,但没有运气。

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

then in 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>

经过大量的搜索和播放,我终于得到了它,在线教程只迎合添加元素的事件,如点击,而不是基于现有数组数据创建的形式组。答案是基于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>