Sunday, May 3, 2020

How to toggle between input type 'password' and 'text' in Angular

Hello Angular developers, Today in this short post I am going to teach you how to toggle between input type 'password' and 'text' using Angular. It is just like when you try login to your gmail account and you see this toggle behaviour while entering your password by pressing small eye icon. You might have seen this feature in many web or mobile apps too. See below picture for your reference:

If you are Angular developer and would like to implement the same behaviour in your Angular app then this post is going to help you. So without delaying further let's jump into the code and believe me it's very simple do it.

In my demo app I have a generated component called 'toggle-input-type' which will looks like below:

In above component I have declared two variables, first one called 'checked' type boolean with default value 'true' and second variable called 'type' type string with default value 'password' which I am gonna use it in our html template later.

I have also declared toggle(event) method which will perform toggle action. In this method we'll have to set type variable value based on certain condition and in this case, if event.checked is true then will change value of 'type' to 'password' else value is 'text'.

Now let's move to our html template. See below is our toggle-input-type.component.html

In above html code I have used 'type' variable in input type attribute. For the toggle button I am using Primeng p-toggleButton to handle toggle behaviour.

In p-toggleButton we can set following property:

  • [(ngModel)]="checked"
  • onLabel=""
  • offLabel=""
  • onIcon="pi pi-eye"
  • offIcon="pi pi-eye-slash"
  • It is also possible to achieve this toggle behaviour in plain javascript as well. See below code:

    Wrap up

    It's time to wrap up and see the toggle behaviour in action by click below demo button:

    If you have like this post then please let me know your opinion by commenting below and sharing this post with other developers.

    No comments:

    Post a Comment