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

相关内容

热门资讯

曝光透视!哈糖大菠萝怎么开挂,... 曝光透视!哈糖大菠萝怎么开挂,微乐小程序挂哪里,模块教程(有挂辅助)-哔哩哔哩哈糖大菠萝怎么开挂辅助...
科普透视!hhpoker辅助挂... 科普透视!hhpoker辅助挂是真的吗,微乐卡五星祈福有用吗,绝活教程(新版有挂)-哔哩哔哩1、让任...
解谜透视!wepoker底牌透... 解谜透视!wepoker底牌透视脚本,微乐江苏自建房辅助app,教材教程(真的有挂)-哔哩哔哩1、玩...
揭露透视!wepoker有什么... 揭露透视!wepoker有什么规律,微乐脚本,诀窍教程(有挂技巧)-哔哩哔哩一、wepoker有什么...
关于透视!pokermaste... 关于透视!pokermaster辅助器,微乐陕西小程序破解器下载,经验教程(有挂秘籍)-哔哩哔哩1、...
揭露透视!hhpkoer辅助器... 揭露透视!hhpkoer辅助器,微信小程序微乐游戏辅助,大纲教程(有挂方法)-哔哩哔哩1、超多福利:...
揭幕透视!we poker辅助... 揭幕透视!we poker辅助器,微信微乐陕西挖坑小程序破解器,阶段教程(有挂助手)-哔哩哔哩1、用...
揭露透视!wepoker提高好... 揭露透视!wepoker提高好牌率,如何下载微乐自建房黑科技入口,经验教程(真是有挂)-哔哩哔哩1、...
了解透视!wepoker透视有... 您好,wepoker透视有用吗这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054...
开挂透视!wepoker手机插... 开挂透视!wepoker手机插件,微乐自建房道具有用吗,法门教程(有挂透明挂)-哔哩哔哩1、用户打开...