Home > Net >  Adding ngIf to script tag in html not working
Adding ngIf to script tag in html not working

Time:03-30

I am trying to add a src to a script in my html file, but only if a condition is true. Otherwise it should not have run the script src. Below is my code so far:

    <script>
      this.booleanValue = JSON.parse(
        sessionStorage.getItem("booleanValue")
      );

      if (this.booleanValue == "true") {
        console.log("true");
      }
    </script>
    <script
      *ngIf="this.booleanValue != true"
      src="code.js"
      async
    ></script>

It console logs the booleanValue as true correctly, however it still runs the script src. It shouldn't because it should only run when false. Does anyone know what I'm doing wrong?

Thanks in advance

CodePudding user response:

You're JSON parsing "booleanValue" when doing :

JSON.parse(
    sessionStorage.getItem("booleanValue")
  )

And you're trying to get value of this.booleanValue directly, it'd be something like 'this.booleanValue.value' when verifying if its value is true or not, or you don't use JSON.parse().

Example: If Session variable is booleanValue => true, you use if(this.booleanValue), but if Session variable is booleanValue => "{value:true}" or "{\"value\":true}", then you use JSON.parse and if(this.booleanValue.value)

  • Related