3

I am getting a `Type 'HTMLElement | null' is not assignable to type 'HTMLElement'. I am trying to validate an email address onkeyup event in angular.

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-mynform',
  templateUrl: './mynform.component.html',
  styleUrls: ['./mynform.component.css']
})
export class MynformComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
    function EmailValidation(): void {
      var email: string = (<HTMLInputElement>document.getElementById("txtEmail")).value;
      var error: HTMLElement = document.getElementById("error");
      error.innerHTML = "";
      var expr: RegExp = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;

      if (!expr.test(email)) {
        error.innerHTML = "Enter valid email address format";
      }
    }
  }

}
<input type="text" name="email" class="notify" autocomplete="off" id="txtEmail" 
onkeyup="EmailValidation();" />
      <span id="error"></span>
Zara
  • 55
  • 7
  • Well, the error is correct; you have something that could be `null`, but you're treating it as if it can't be `null`. What is the question? – kaya3 Aug 23 '21 at 12:17
  • what should i do to solve the null error problem ?? – Zara Aug 23 '21 at 12:21
  • 1
    Does this answer your question? [How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?](https://stackoverflow.com/questions/40349987/how-to-suppress-error-ts2533-object-is-possibly-null-or-undefined) – kaya3 Aug 23 '21 at 12:24

1 Answers1

3

document.getElementById(id) may return null. If you can guarantee that the element with id "error" exists then you should be able to fix it by adding a ! after: var error: HTMLElement = document.getElementById("error")!.

Alternatively, change the type of the error variable to allow null: var error: HTMLElement | null = document.getElementById("error")

Matt U
  • 4,970
  • 9
  • 28