Angular响应式表单,移除的元素仍然进行验证
创始人
2024-10-30 08:30:34
0

在Angular中,可以通过使用FormArray和FormGroup来实现响应式表单,以便在移除元素时仍然进行验证。下面是一个示例代码:

首先,创建一个FormGroup来表示整个表单:

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

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

  ngOnInit() {
    this.form = new FormGroup({
      items: new FormArray([])
    });
  }

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

  addItem() {
    const item = new FormGroup({
      name: new FormControl('', Validators.required),
      quantity: new FormControl('', Validators.required)
    });

    this.items.push(item);
  }

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

然后,在HTML模板中使用FormArray来渲染表单和验证错误信息:

在上面的代码中,我们使用FormArray来表示表单中的多个项目,并使用formGroupName和formControlName来绑定每个项目的FormControl。在移除元素时,调用removeAt方法来从FormArray中删除相应的FormGroup。

这样,当移除元素时,Angular仍然会对剩余的元素进行验证,并在表单提交时显示错误信息。

相关内容

热门资讯

透视解迷!聚星ai辅助工具下载... 透视解迷!聚星ai辅助工具下载(透视)wepoker怎么设置透视,教程方针(有挂秘笈)-哔哩哔哩1....
wepoker破解器激活码!w... wepoker破解器激活码!wepoker免费透视脚本(透视)器-其实揭露真的有挂1、wepoker...
模拟器打开hhpoker!po... 模拟器打开hhpoker!pokemmo辅助官网(透视)软件-原来总结有挂1、该软件可以轻松地帮助玩...
透视了解!wpk俱乐部怎么透视... 透视了解!wpk俱乐部怎么透视(透视)hhpoker真的假的,教程资料(有挂讲解)-哔哩哔哩1、进入...
wepoker私局辅助!wpk... wepoker私局辅助!wpk透视工作室(透视)软件-真是解密真的是有挂1、wepoker私局辅助透...
透视详细!aapoker真的假... 透视详细!aapoker真的假的(透视)werplan怎么透视,教程办法(有挂神器)-哔哩哔哩1、w...
newpoker怎么安装脚本!... newpoker怎么安装脚本!约局吧德州真的有透视挂吗(透视)教程-总是了解是真的挂在进入约局吧德州...
透视分享!pokermaste... 透视分享!pokermaster辅助器(透视)大菠萝免费辅助器,教程手册(有挂分析)-哔哩哔哩运大菠...
wepoker免费脚本弱密码!... wepoker免费脚本弱密码!wepoker底牌透视脚本(透视)软件-一贯教你是有挂1、操作简单,无...
透视详情!poker红龙辅助(... 透视详情!poker红龙辅助(透视)wepoker辅助软件视频,教程模块(有挂技巧)-哔哩哔哩wep...