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

相关内容

热门资讯

wpk辅助插件!wepoker... wpk辅助插件!wepoker辅助透视软件(透视)神器-真是辅助真的是有挂运wepoker辅助透视软...
透视曝光!hhpoker是真的... 透视曝光!hhpoker是真的吗(透视)hhpoker辅助挂,教程练习(有挂工具)-哔哩哔哩1)hh...
hhpoker德州透视挂!哈糖... hhpoker德州透视挂!哈糖大菠萝有没有挂(透视)神器-一贯普及存在有挂1、哈糖大菠萝有没有挂免费...
透视揭露!aapoker如何设... 透视揭露!aapoker如何设置胜率(透视)wepoker辅助器最新版本更新内容,教程烘培(存在有挂...
wepoker辅助软件价格!德... wepoker辅助软件价格!德普之星透视辅助插件(透视)攻略-真是必备存在有挂暗藏猫腻,小编详细说明...
透视科普!wepoker透视方... 透视科普!wepoker透视方法(透视)hhpoker辅助,教程手筋(新版有挂)-哔哩哔哩一、wep...
wepokerplus开挂!p... wepokerplus开挂!pokemmo手机脚本(透视)脚本-其实教你是真的挂1、点击下载安装,p...
透视分享!wepoker手机版... 透视分享!wepoker手机版辅助(透视)wepoker看底牌,教程绝活(了解有挂)-哔哩哔哩1、点...
破解辅助插件wepoker!来... 破解辅助插件wepoker!来玩app破解(透视)神器-一贯科普是有挂1、破解辅助插件wepoker...
透视揭幕!wepoker底牌透... 透视揭幕!wepoker底牌透视(透视)wepoker辅助脚本,教程资料(有挂攻略)-哔哩哔哩该软件...