如何检查Angular / Ionic中的两个字段是否相等?

vin*_*svl 3 ionic-framework ionic3 angular

我想检查两个字段的值是否相同,这些字段必须通过参数传递给验证函数,我是这样做的,问题是获取不到字段的值,出现null,因为我可以正确动态地获取值吗?

我的表单构建器,我正在使用匹配功能来检查 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]
});
Run Code Online (Sandbox Code Playgroud)

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

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

mal*_*awi 5

You need to create a custom formGroup validator to check the value of the form controls values and check theme

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

Custom Validator function

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

stackblitz demo