angular利用FormArray创建动态响应式表单

FormArray 是 FormGroup 之外的另一个选择,用于管理任意数量的匿名控件。像 FormGroup 实例一样,你也可以往 FormArray 中动态插入和移除控件,并且 FormArray 实例的值和验证状态也是根据它的子控件计算得来的。不过,你不需要为每个控件定义一个名字作为 key,因此,如果你事先不知道子控件的数量,这就是一个很好的选择。

要定义一个动态表单,请执行以下步骤:

1.导入 FormArray 类。

2.定义一个 FormArray 控件。

3.使用 getter 方法访问 FormArray 控件。

4.在模板中显示这个表单数组。

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<p>把表单控件分组</p>
 
 
<form [formGroup]="profileForm"  (ngSubmit)="onSubmit()">
 
    <label for="first-name">First Name: </label>
    <!-- 配合表单使用要用"formControlName",单个控件使用"formControl" -->
    <input id="first-name" type="text" formControlName="firstName">
   
    <label for="last-name">Last Name: </label>
    <input id="last-name" type="text" formControlName="lastName">
     
    <div formGroupName="address">
        <!-- 在模板中对这个嵌套表单分组。 -->
        <h2>Address</h2>
       
        <label for="street">Street: </label>
        <input id="street" type="text" formControlName="street">
       
        <label for="city">City: </label>
        <input id="city" type="text" formControlName="city">
       
        <label for="state">State: </label>
        <input id="state" type="text" formControlName="state">
       
        <label for="zip">Zip Code: </label>
        <input id="zip" type="text" formControlName="zip">
      </div>
      <div formArrayName="aliases">
        <h2>Aliases</h2>
      <strong>  <button type="button" (click)="addAlias()">+ Add another alias</button>
       
        <div *ngFor="let alias of aliases.controls; let i=index">
          <!-- The repeated alias template -->
          <label for="alias-{{ i }}">Alias:</label>
          <input id="alias-{{ i }}" type="text" [formControlName]="i">
        </div></strong>
      </div>
    <button type="submit" class="btn btn-secondary" (click)="<strong>addAlias</strong>()">动态添加表单控件</button>
 </form>

  

复制代码
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { FormGroup, FormControl,FormArray, FormBuilder } from '@angular/forms';

@Component({
  selector: 'app-profile-editor',
  templateUrl: './profile-editor.component.html',
  styleUrls: ['./profile-editor.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ProfileEditorComponent {
  // profileForm = new FormGroup({
  //   firstName: new FormControl(''),
  //   lastName: new FormControl(''),
  //   address: new FormGroup({
  //     street: new FormControl(''),
  //     city: new FormControl(''),
  //     state: new FormControl(''),
  //     zip: new FormControl('')
  //   })
  // })


  // 当需要与多个表单打交道时,手动创建多个表单控件实例会非常繁琐。FormBuilder 服务提供了一些便捷方法来生成表单控件。
  //FormBuilder 在幕后也使用同样的方式来创建和返回这些实例,只是用起来更简单。
  constructor(private fb: FormBuilder) {}
  // 在上面的例子中,你可以使用 group() 方法,用和前面一样的名字来定义这些属性。
  // 这里,每个控件名对应的值都是一个数组,这个数组中的第一项是其初始值。
  profileForm = this.fb.group({
    firstName: [''],
    lastName: [''],
    address: this.fb.group({
      street: [''],
      city: [''],
      state: [''],
      zip: ['']
    }),
    // FormArray 是 FormGroup 之外的另一个选择,用于管理任意数量的匿名控件。无需给控件设置key
    // 你也可以往 FormArray 中动态插入和移除控件,
    aliases: this.fb.array([
      this.fb.control('')
    ])
  });

  //访问FormArray控件
  get aliases() {
    return this.profileForm.get('aliases') as FormArray;
  }
  addAlias() {
    this.aliases.push(this.fb.control(''));
  }
  onSubmit() {
    console.warn(this.profileForm.value);
    console.warn(this.profileForm.get('firstName')!.value);
  }

  updateProfile() {
    // patchValue可以更新表单的部分数据
    this.profileForm.patchValue({
      firstName: 'Nancy',
      address: {
        street: '123 Drew Street'
      }
    });
  }
 
}
复制代码

 

posted @   赵辉Coder  阅读(558)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示