Home > Back-end >  Angular target.getAttribute() check null condition
Angular target.getAttribute() check null condition

Time:10-07

I was having some problem with Angular. I am trying to set different value accordingly. Below as my code:

 console.log("JJJJJJJ "   target.getAttribute("timingId"));
        console.log("KKKKKKKKK "   target.getAttribute("index"));
        if(target.getAttribute("timingId") != null){
          console.log("INSIDE ORI SET");
          this.timingId = target.getAttribute("timingId");
        } else {
          console.log("INSIDE INDEX SET");
          this.timingId = target.getAttribute("index");
        }
        console.log("HAHAHAHAHAHAH "   this.timingId);

What I am trying to do is check in timindId from getAttribute(), if it is not null, then set it. If it is null, getAttribute() from another field then set it. My console as per following:

JJJJJJJ null
KKKKKKKKK 1
INSIDE ORI SET
HAHAHAHAHAHAH null

I am not sure why when it is detected as null, it will not go into the else statement and set the value. Any ideas?

EDITED

console.log(typeof target.getAttribute("timingId"));
        console.log("JJJJJJJ "   target.getAttribute("timingId"));
        console.log("KKKKKKKKK "   target.getAttribute("index"));
        if(target.getAttribute("timingId") != null || target.getAttribute("timingId") != "null"){
          console.log("INSIDE ORI SET");
          this.timingId = target.getAttribute("timingId");
        } else {
          console.log("INSIDE INDEX SET");
          this.timingId = target.getAttribute("index");
        }
        console.log("HAHAHAHAHAHAH "   this.timingId);

Thanks!

CodePudding user response:

You should check for "null" as a string in the if statement.

const timingId = target.getAttribute("timingId")
if (timingId != null && timingId !== "null") {
   this.timingId = timingId
} else {
   this.timingId = target.getAttribute("index");
}
  • Related