Search code examples
angulartypescriptformsionic-framework

Password Visibility Toggle


I'm trying to use a typescript function in my page to change the icon that toggles the password visibility. this is how it's supposed to work: i press a button (in this case, a clickable icon), the icon changes and the property "type" in the input should change to "text", to allow the user to see what they have entered in this field. then, when pressed again, the icon should change to the default value and the input type should return to "password".

this is my code:

togglePasswordVisibility() {
    document.querySelector("#input2").setAttribute("type", "password")
    
    document.querySelector("#passwordIcon").setAttribute("name", "eye-off")
    
    if (document.querySelector('#passwordIcon').getAttribute('name') == 'eye-off') {
      
      document.querySelector('#passwordIcon').setAttribute("name", "eye")
    }

the problem is that it only works once, and I want it to work multiple times. Can someone help me?


Solution

  • Your code basically states:

    • Set the type to password
    • If the type is password, set it to text

    But the second part of that will always be true, that's why it only works once. So you should change it to:

    togglePasswordVisibility() {    
      if (document.querySelector('#passwordIcon').getAttribute('name') == 'eye-off') {
        document.querySelector("#input2").setAttribute("type", "text")
        document.querySelector('#passwordIcon').setAttribute("name", "eye-off");
      } else {
        document.querySelector("#input2").setAttribute("type", "password");
        document.querySelector("#passwordIcon").setAttribute("name", "eye");
      }
    }