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

相关内容

热门资讯

透视苹果版!智星德州插件(透视... 透视苹果版!智星德州插件(透视)微乐家乡破解版(确实真的有辅助工具)-哔哩哔哩1、微乐家乡破解版辅助...
长期以来!wepoker辅助插... 长期以来!wepoker辅助插件功能(透视)游戏黑科技夫追求(一直存在有辅助app)-哔哩哔哩1.游...
透视科技!拱趴大菠萝作必弊方法... 透视科技!拱趴大菠萝作必弊方法(透视)中至赣州黑科技辅助软件(本来有辅助辅助器)-哔哩哔哩1、全新机...
透视智能ai!淘宝买wepok... 透视智能ai!淘宝买wepoker透视有用吗(透视)玩吧辅助脚本(一直是有辅助辅助器)-哔哩哔哩1、...
透视肯定!wepoker辅助器... 透视肯定!wepoker辅助器是真的吗(透视)心悦海南苹果版辅助(原来是真的辅助神器)-哔哩哔哩1、...
一直以来!wepoker钻石怎... 一直以来!wepoker钻石怎么看底牌(透视)丫丫老陕开挂(好像真的是有辅助下载)-哔哩哔哩1、丫丫...
透视实锤!wepoker怎么提... 透视实锤!wepoker怎么提高运气(透视)赣湘互娱挂(都是存在有辅助神器)-哔哩哔哩1、赣湘互娱挂...
透视辅助!newpoker脚本... 透视辅助!newpoker脚本(透视)四川微乐小程序辅助器(都是是真的辅助平台)-哔哩哔哩;一、四川...
为切实保障!哈糖大菠萝攻略(透... 为切实保障!哈糖大菠萝攻略(透视)广东雀神智能插件(本来真的是有辅助安装)-哔哩哔哩所有人都在同一条...
透视好友房!wepoker俱乐... 透视好友房!wepoker俱乐部辅助(透视)广西友乐免费辅助使用视频(切实是有辅助软件)-哔哩哔哩1...