【问题标题】:Angular Reactive Form, dynamically create form controlsAngular Reactive Form,动态创建表单控件
【发布时间】:2021-04-27 05:29:57
【问题描述】:

我有一个需要有一个或多个简单输入字段的响应式表单。所以我正在做一个 *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([])
  });

【问题讨论】:

标签: angular forms


【解决方案1】:

非常简单.. 只需在表单或任何表单字段上使用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()
}

你当然可以像这样听表单对象..

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()
}

不要忘记取消订阅!!

【讨论】:

    猜你喜欢
    • 2020-09-30
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-05
    • 2018-10-31
    • 2018-08-03
    • 2022-01-05
    相关资源
    最近更新 更多