首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

使用动态formArray Angular 7中的自定义验证器比较两个值

在Angular 7中,使用动态formArray时,可以通过自定义验证器来比较两个值。自定义验证器是一个函数,它接收一个控件作为参数,并返回一个验证结果对象。

首先,我们需要在组件中创建一个自定义验证器函数。这个函数可以在组件类中定义,也可以在单独的验证器文件中定义。以下是一个示例的自定义验证器函数,用于比较两个值:

代码语言:txt
复制
import { AbstractControl, ValidatorFn } from '@angular/forms';

export function compareValuesValidator(controlName1: string, controlName2: string): ValidatorFn {
  return (control: AbstractControl): { [key: string]: any } | null => {
    const value1 = control.get(controlName1)?.value;
    const value2 = control.get(controlName2)?.value;

    if (value1 !== value2) {
      return { compareValues: true };
    }

    return null;
  };
}

在这个示例中,compareValuesValidator函数接收两个控件名作为参数,然后返回一个验证器函数。验证器函数接收一个控件作为参数,并在该函数中比较两个控件的值。如果两个值不相等,则返回一个包含compareValues属性的验证结果对象,表示验证失败;否则返回null,表示验证通过。

接下来,在组件中使用这个自定义验证器。假设我们有一个动态formArray,其中包含两个控件,分别是password和confirmPassword。我们可以在组件类中的表单初始化方法中使用自定义验证器,如下所示:

代码语言:txt
复制
import { FormGroup, FormBuilder } from '@angular/forms';
import { compareValuesValidator } from './compare-values.validator';

@Component({
  selector: 'app-my-form',
  templateUrl: './my-form.component.html',
  styleUrls: ['./my-form.component.css']
})
export class MyFormComponent implements OnInit {
  form: FormGroup;

  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.form = this.formBuilder.group({
      passwords: this.formBuilder.array([
        this.formBuilder.control(''),
        this.formBuilder.control('')
      ], { validators: compareValuesValidator('password', 'confirmPassword') })
    });
  }
}

在这个示例中,我们使用formBuilder创建了一个动态formArray,并在validators选项中传入了compareValuesValidator函数,并指定了需要比较的两个控件名。

最后,在模板中显示验证错误信息。我们可以通过form.get方法获取到动态formArray的验证状态,并根据验证状态显示相应的错误信息。以下是一个示例的模板代码:

代码语言:txt
复制
<form [formGroup]="form">
  <div formArrayName="passwords">
    <div *ngFor="let password of form.get('passwords').controls; let i = index">
      <input type="password" [formControlName]="i">
    </div>
  </div>
  <div *ngIf="form.get('passwords').errors?.compareValues">
    Passwords do not match.
  </div>
</form>

在这个示例中,我们使用formArrayName指令将动态formArray绑定到模板中的div元素,并使用formControlName指令将每个控件绑定到对应的input元素上。然后,我们使用*ngIf指令根据验证状态显示错误信息。

这样,当用户输入的两个密码不相等时,会显示"Passwords do not match."的错误信息。

推荐的腾讯云相关产品和产品介绍链接地址:

  • 云服务器(CVM):https://cloud.tencent.com/product/cvm
  • 云数据库 MySQL 版(CDB):https://cloud.tencent.com/product/cdb
  • 云原生容器服务(TKE):https://cloud.tencent.com/product/tke
  • 人工智能平台(AI Lab):https://cloud.tencent.com/product/ailab
  • 物联网开发平台(IoT Explorer):https://cloud.tencent.com/product/iothub
  • 移动推送服务(信鸽):https://cloud.tencent.com/product/tpns
  • 云存储(COS):https://cloud.tencent.com/product/cos
  • 区块链服务(BCS):https://cloud.tencent.com/product/bcs
  • 腾讯云元宇宙:https://cloud.tencent.com/solution/virtual-universe
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券