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仍然会对剩余的元素进行验证,并在表单提交时显示错误信息。

相关内容

热门资讯

透视有挂!wepoker私人局... 透视有挂!wepoker私人局辅助器怎么用(透视)hhpkoer辅助器视频,教程指南书(有挂秘笈)-...
透视推荐!aapoker透视怎... 透视推荐!aapoker透视怎么用(透视)智星德州插件2024最新版,教程法子(真的有挂)-哔哩哔哩...
透视普及!hhpoker透视码... 透视普及!hhpoker透视码(透视)aapoker公共底牌,教程模板(有挂规律)-哔哩哔哩1、上手...
透视揭露!hhpoker有没有... 透视揭露!hhpoker有没有开挂(透视)pokemmo辅助器手机版下载,教程步骤(有挂秘诀)-哔哩...
透视了解!hhpkoer辅助挂... 透视了解!hhpkoer辅助挂是真的吗(透视)哈糖大菠萝攻略,教程学习(证实有挂)-哔哩哔哩1、金币...
透视解迷!约局吧怎么看有没有挂... 透视解迷!约局吧怎么看有没有挂(透视)wepoker有没有机器人,教程窍门(确实有挂)-哔哩哔哩亲,...
透视推荐!wepokerplu... 透视推荐!wepokerplus透视脚本免费(透视)菠萝德州透视脚本,教程教材(存在有挂)-哔哩哔哩...
透视辅助!wepoker辅助器... 透视辅助!wepoker辅助器安装包(透视)wepoker插件程序激活码,教程阶段(有挂分析)-哔哩...
透视总结!wepoker安装教... 透视总结!wepoker安装教程(透视)约局吧开挂神器是真的吗,教程方式(有挂猫腻)-哔哩哔哩所有人...
透视详细!wepoker辅助器... 透视详细!wepoker辅助器安装包(透视)wepoker辅助器安装包,教程手筋(竟然有挂)-哔哩哔...