【问题标题】:Angular - Error: Object is possibly null in password change validatorAngular - 错误:密码更改验证器中的对象可能为空
【发布时间】:2021-09-16 08:02:21
【问题描述】:

我在 Angular-12 中有这个密码更改验证器:

import { AbstractControl, ValidationErrors } from '@angular/forms';

export class OldPwdValidators {
  static shouldBe1234(control: AbstractControl) : Promise<ValidationErrors | null> {
    return new Promise((resolve,reject) => {
        if(control.value !== '1234')
          resolve({ shouldBe1234: true });
        else
          resolve(null);
    });
  }

  static matchPwds(control: AbstractControl) {
    let newPwd2 = control.get('newPwd');
    let confirmPwd2 = control.get('confirmPwd');
    if(newPwd2.value !== confirmPwd2.value){
      return { pwdsDontMatch: true };
    }
    return null;
  }
}

我收到了这个错误:

对象可能为空

这两行高亮显示:

newPwd2.value

确认Pwd2.value

【问题讨论】:

标签: angular


【解决方案1】:

根据AbstractControl get()

返回:AbstractControl |空

因此newPwd2confirmPwd2 可能是null


解决方案 1

如果您确认newPwdconfirmPwd 控件都存在(保证),您可以将其转换为AbstractControl

let newPwd2: AbstractControl = control.get('newPwd') as AbstractControl;
let confirmPwd2: AbstractControl = control.get('confirmPwd') as AbstractControl;

Solution 1 on StackBlitz


解决方案 2

在访问其属性之前检查newPwdconfirmPwd 不得为nullundefined

static matchPwds(control: AbstractControl) {
  let newPwd2 = control.get('newPwd');
  let confirmPwd2 = control.get('confirmPwd');

  if (newPwd2 && confirmPwd2) {
    if (newPwd2.value !== confirmPwd2.value) {
      return { pwdsDontMatch: true };
    }
  }
  return null;
}

Solution 2 on StackBlitz

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 2020-06-03
    • 2019-01-25
    • 2016-11-15
    • 1970-01-01
    • 2014-02-03
    • 1970-01-01
    相关资源
    最近更新 更多