如何检查两个场在角度/离子上是否相等? [英] How to check if two fields are equal in Angular / Ionic?

查看:9
本文介绍了如何检查两个场在角度/离子上是否相等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查两个字段的值是否相同,这些字段必须通过参数传递给验证函数,我正在这样做,问题是它无法获取字段的值,它显示为空,因为我可以正确且动态地获取值吗?

我的表单生成器,我正在使用Match函数检查cell_phone和确认字段。

this.recharge = this.formBuilder.group({
  cell_phone: ['', Validators.required, Validations.match('cell_phone', 'cell_phone_confirmation')],
  cell_phone_confirmation: ['', [Validators.required]],
  value: ['', Validators.required],
  operator_id: ['', Validators.required]
});

在我的函数中,控制台日志为空:

static match(field1: string, field2: string){
  return (group: FormGroup) => {
    console.log(group.get(field1));
  }
}

推荐答案

您需要创建自定义Form Group验证器来检查表单控件值的值和检查主题

this.recharge = formBuilder.group({
  cell_phone: ['', Validators.required],
  cell_phone_confirmation: ['', Validators.required],
},
  {
    validator: checkMatchValidator('cell_phone', 'cell_phone_confirmation')
  }
);

自定义验证器函数

export function checkMatchValidator(field1: string, field2: string) {
  return function (frm) {
    let field1Value = frm.get(field1).value;
    let field2Value = frm.get(field2).value;

    if (field1Value !== '' && field1Value !== field2Value) {
      return { 'notMatch': `value ${field1Value} is not equal to ${field2}` }
    }
    return null;
  }
}

stackblitz demo🚀🚀

这篇关于如何检查两个场在角度/离子上是否相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆