0

Currently, I am working on user registration in Angular. Here is my part of code where I'm trying to compare Password and ConfirmPassword:

comparePasswords(fb: FormGroup) {
let confirmPswrdCtrl = fb.get('ConfirmPassword');

if (confirmPswrdCtrl.errors == null || 'passwordMismatch' in confirmPswrdCtrl.errors) {
  if (fb.get('Password').value != confirmPswrdCtrl.value)
    confirmPswrdCtrl.setErrors({ passwordMismatch: true });
  else
    confirmPswrdCtrl.setErrors(null);
 }
}

The problem is that Angular warns me about confirmPswrdCtrl, that it can be possibly null:

error TS2531: Object is possibly 'null'.

What's wrong and how can I solve this? Thanks in advance.

puzzy.x
  • 61
  • 5

2 Answers2

3

you need to let typescript know it's there. simplest way is as so:

let confirmPswrdCtrl = fb.get('ConfirmPassword') as FormControl;
bryan60
  • 28,215
  • 4
  • 48
  • 65
  • Is good, but now it says that fb.get('Password') is possibly null... – puzzy.x Apr 22 '21 at 21:11
  • 1
    well you could do the same thing like `let passwordCtrl = fb.get('password') as FormControl` or just assert not null like `if (fb.get('Password')!.value != confirmPswrdCtrl.value)` – bryan60 Apr 22 '21 at 21:13
  • Thank you bryan60 ! You're the best! – puzzy.x Apr 22 '21 at 21:15
  • @bryan60 side question, you are using `fb.get('Password')!.value` but I have never seen `!` used like this before. could you explain it real quick or share a link – rhavelka Apr 22 '21 at 21:24
  • never mind, I found a [stackoverflow post](https://stackoverflow.com/questions/38874928/operator-in-typescript-after-object-method) – rhavelka Apr 22 '21 at 21:28
  • yea, non null assertion operator – bryan60 Apr 22 '21 at 22:55
0

Open tsconfig.json and add "strictNullChecks": false to angularCompilerOptions

{
  ...
  "angularCompilerOptions": {
    "strictNullChecks": false,
    ...
  }
}
Ricardo Saracino
  • 1,345
  • 2
  • 16
  • 37