Angular 6中的FormArray和HTML循环
创始人
2024-10-16 10:30:32
0

在Angular 6中,可以使用FormArray来处理表单中的动态字段集合。下面是一个示例,展示了如何使用FormArray和HTML循环来实现动态字段的添加和删除。

首先,在组件的模板中,定义一个FormArray,并使用ngFor指令来循环显示FormArray中的字段:

接下来,在组件的代码中,需要初始化FormArray,并提供添加和删除字段的方法:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';

@Component({
  selector: 'app-my-form',
  templateUrl: './my-form.component.html',
  styleUrls: ['./my-form.component.css']
})
export class MyFormComponent implements OnInit {
  myForm: FormGroup;

  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.myForm = this.fb.group({
      items: this.fb.array([])
    });
  }

  get items() {
    return this.myForm.get('items') as FormArray;
  }

  addItem() {
    this.items.push(this.fb.control(''));
  }

  removeItem(index: number) {
    this.items.removeAt(index);
  }
}

在上面的代码中,我们首先使用FormBuilder创建了一个空的FormGroup,并在其中添加了一个空的FormArray。然后,我们定义了两个方法addItem()和removeItem(),用于向FormArray中添加和删除字段。

注意,由于items是一个FormArray类型,我们需要通过将其转换为FormArray类型来获取其控制器。

最后,确保在模块中导入并将FormsModule和ReactiveFormsModule添加到imports数组中:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { MyFormComponent } from './my-form.component';

@NgModule({
  imports: [BrowserModule, FormsModule, ReactiveFormsModule],
  declarations: [AppComponent, MyFormComponent],
  bootstrap: [AppComponent]
})
export class AppModule { }

这样,你就可以在Angular 6中使用FormArray和HTML循环来处理动态字段集合了。

相关内容

热门资讯

2分钟辅助!hhpoker透视... 2分钟辅助!hhpoker透视脚本,wepoker有透视吗,教程书教程(有挂头条)1、超多福利:超高...
第七分钟辅助!wepoker透... 第七分钟辅助!wepoker透视app下载,aa poker辅助包,讲义教程(有挂分享)一、wepo...
第八分钟辅助!wepoker怎... 第八分钟辅助!wepoker怎么开辅助,xpoker辅助器,模块教程(的确有挂)1、不需要AI权限,...
一分钟辅助!wepoker有没... 一分钟辅助!wepoker有没有挂,pokemmo脚本辅助器,讲义教程(有挂教学)1、完成pokem...
第一分钟辅助!hhpoker是... 第一分钟辅助!hhpoker是真的还是假的,wepoker辅助器,阶段教程(有挂技巧)1、金币登录送...
8分钟辅助!hhpoker辅助... 8分钟辅助!hhpoker辅助挂,wejoker私人辅助软件,窍要教程(有挂分析)1、玩家可以在we...
第6分钟辅助!xpoker透视... 第6分钟辅助!xpoker透视辅助,wejoker内置辅助,窍门教程(有挂秘诀)该软件可以轻松地帮助...
第六分钟辅助!aapoker公... 第六分钟辅助!aapoker公共底牌,aapoker怎么设置抽水,办法教程(真是有挂)1、在aapo...
9分钟辅助!wepoker辅助... 9分钟辅助!wepoker辅助真的假的,aapoker透视脚本下载,手册教程(有挂解密)1、首先打开...
第7分钟辅助!wepoker底... 第7分钟辅助!wepoker底牌透视脚本,wepoker黑侠破解,模板教程(揭秘有挂)1、wepok...