簡體   English   中英

Angular Reactive Form,動態創建表單控件

[英]Angular Reactive Form, dynamically create form controls

我有一個需要有一個或多個簡單輸入字段的反應形式。 因此,我正在對 go ovr 對 object 數組進行 *ngFor 操作,並且可以成功創建標簽。 我也可以創建輸入字段,但我不知道如何跟蹤其中輸入的值。 我需要收集用戶輸入的輸入並將其發送到后端。

我該怎么做? 我做了研究,發現我應該使用一個數組來保存所有可能數量的生成輸入字段。 但是我如何為它創建表單控件。

    <form [formGroup]="SignupForm" (ngSubmit)="onSubmit()">
      <div class="form-group p-mb-4"  *ngFor="let _insertField of actionsetSelected; let i=index">
         <label class="formLabel" *ngIf="_insertField" for="userInput">{{_insertField.name}}</label>
         <input type="text" class="form-control" id="insertNames" [formControlName]="i">
      </div>
    <button label="Submit" ></button>
</form>

 

in my ts:

 
this.SignupForm = new FormGroup({
    'insertNames':new FormArray([])
  });

它非常簡單.. 只需在表單或任何表單字段上使用valueChanges .. 例如。

假設我有一個名為email的表單,在我的 ts 文件中,我可以執行以下操作。

ngAfterViewInit() {
    this.SignupForm.email.valueChanges.pipe(
       tap(value: string) => { // value is the email the user entered
    
           // do what ever you want with value     

       }
    ).subscribe()
}

您當然可以像這樣收聽 object 表格。

ngAfterViewInit() {
    this.SignupForm.valueChanges.pipe(
       tap(value: string) => { // value is your form object containing all the fields
    
           // do what ever you want with value     

       }
    ).subscribe()
}

不要忘記取消訂閱!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM