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

相关内容

热门资讯

透视存在!sohoo竞技联盟辅... 透视存在!sohoo竞技联盟辅助器,德普之星有透视辅助吗(透视)推荐教程(有挂方略)-哔哩哔哩1、上...
透视规律!hhpoker开挂教... 透视规律!hhpoker开挂教程,wepoker辅助透视(透视)总结教程(有挂秘笈)-哔哩哔哩1、不...
透视新版!拱趴大菠萝机器人,n... 透视新版!拱趴大菠萝机器人,newpoker脚本(透视)开挂教程(有挂猫腻)-哔哩哔哩1、拱趴大菠萝...
透视神器!wpk刷入池率脚本,... 透视神器!wpk刷入池率脚本,德州透视是真的吗(透视)推荐教程(的确有挂)-哔哩哔哩1、完成德州透视...
据了解!aapoker发牌逻辑... 据了解!aapoker发牌逻辑,wepoker可以开透视吗(透视)推荐教程(真实有挂)-哔哩哔哩1、...
现场直击!wepoker有辅助... 现场直击!wepoker有辅助吗,wepoker有没有透视方法(透视)科普教程(有挂教学)-哔哩哔哩...
透视黑科技!hhpoker怎么... 透视黑科技!hhpoker怎么防辅助,wepoker科技辅助器(透视)解密教程(今日头条)-哔哩哔哩...
于此同时!德州机器人代打脚本,... 于此同时!德州机器人代打脚本,aapoker如何设置胜率(透视)关于教程(真实有挂)-哔哩哔哩在进入...
透视攻略!wepoker到底有... 透视攻略!wepoker到底有没有透视,poker红龙辅助(透视)必备教程(有挂教学)-哔哩哔哩;1...
透视辅助!wepoker软件靠... 透视辅助!wepoker软件靠谱么,来玩德州破解器(透视)了解教程(有挂细节)-哔哩哔哩在进入wep...