Here's a guide on using a button to toggle the display of password value in Angular, allowing users to easily hide

I have successfully implemented an Angular Directive to toggle the visibility of password fields in a form. However, I am facing an issue with updating the text displayed on the button based on the state of the input field.

Is there a way for me to dynamically change the button text to 'HIDE' when the user clicks to reveal the password, and then revert it back to 'SHOW' when the user clicks again to hide the password?

Here is the code snippet that forms the basis of this functionality:

import { Directive, ElementRef, HostListener, Renderer2 } from '@angular/core';

@Directive({
  selector: '[passToggle]'
})
export class ToggleDirective {
  visible: boolean = false;

  constructor(private el: ElementRef, private renderer: Renderer2) { }

  div = this.renderer.createElement('div');
  span = this.renderer.createElement('span');

  ngOnInit() {
    this.buildInputAppend();
  }

  buildInputAppend () {
    this.renderer.addClass(this.div, 'input-group-append');
    this.renderer.addClass(this.span, 'input-group-text');

    const text = this.renderer.createText('Show');

    this.renderer.appendChild(this.span, text);
    this.renderer.appendChild(this.div, this.span);

    this.renderer.appendChild(this.el.nativeElement, this.div);
  }

  @HostListener('click') onClick() {
    this.visible = !this.visible;

    const parent = this.el.nativeElement.parentNode;
    const input = this.el.nativeElement.firstChild;

    if (!this.visible) {
      input.setAttribute('type', 'text');
    } else {
      input.setAttribute('type', 'password');
    }
  }


}

The HTML template structure is as follows:

<div class="form-group">
  <div class="input-group" passToggle>
    <input class="form-control" type="password"formControlName="password" >
  </div>
</div>

If you want to see a demonstration of this feature in action, check out this link: Password Toggle Demo

Answer №1

To complete your onClick() method, simply insert the following code snippet:

this.span.innerText = this.toggleName('Display', 'Conceal');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular 2 code test coverage

Looking to calculate the code coverage of my Angular 2 code. Wondering if there are any plugins available for VS Code or WebStorm that can assist with this. My unit testing is done using Jasmine and Karma. ...

Flawed reasoning in determining the selection of checkboxes

Take a look at the code snippet below, featuring multiple checkboxes with corresponding fields: <Checkbox checked={checked[element]} onChange={(e) => { setChecked({ ...checked, [e.target.name]: !checked[e ...

Customizing the placeholder font size in Material UI Autocomplete using ReactJS

Is there a way to change the placeholder font size for Material UI Autocomplete? https://i.stack.imgur.com/x71k2.png <Autocomplete multiple id="tags-outlined" options={top100F ...

Getting a null value for active user after completing the sign-in process

I am using local storage to store username and password. However, I am encountering an issue where the active user is returning null after a certain line of code, and I am unsure why. console.log("I am the Active user: " + activeUser); const me ...

JavaScript Date Validation: Ensuring Proper Dates

I am working with a date string that is in the format of "DD-MM-YYYY" and have successfully validated it using this code: var dateFormat = /(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[012])-\d{4}/ ; if(!startDate.match(dateFormat)){ alert("'Start Dat ...

Control the switch for CSS selectors

Consider the following scenario where CSS rules are defined: <style> table {background:red;} div {background:green;} </style> In addition, there is HTML code that calls a JavaScript function: <table onclick="tu ...

Understanding variable scopes in the success callback function of a JQuery post request

I am encountering an issue with passing the AJAX success array from one function to another. It seems that I am unable to transfer the data stored in a variable within the success section of the AJAX function to the parent function for return. I tried to ...

The debate between utilizing multiple @Input() decorators versus a single @Input() decorator in Angular

When it comes to efficiency in Angular, what is the best way to transfer data into a child component - using one @Input() decorator or multiple @Input() decorators? I have been considering two possible solutions: either sending all the data as a single ob ...

Vue HeadlessUI Error: The function vue.defineComponent is not recognized

Trying to incorporate @headlessui/vue into my nuxt project has been a challenge. My attempt at using it looks like this: <template> <Menu> <MenuItems> <MenuItem>Item</MenuItem> </MenuItems> </Menu&g ...

Creating a custom progress bar using Javascript and Jquery

I developed a progress bar that is fully functional. Here is the HTML structure: <div class="progress"> <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style ...

Unable to get the deletion functionality to work for Dropzone.js and PHP script

I am currently using dropzone to handle file uploads. My goal is to delete the files on the server when the user clicks on the removeLink. I have implemented an Ajax function that calls a .php site for this purpose. However, I am facing an issue where I am ...

What is the most effective method to implement an isLoggedIn function in AngularJS that is accessible from any controller or template?

I'm looking to create an isLoggedIn() function that can be accessed by both controllers and templates. Templates need this function to execute something like ng-show="isLoggedIn()". What would be the most efficient way to achieve this? If using a ser ...

Angular Testing: Discovering the best practices for asserting expectations post function execution

I'm currently facing a challenge while unit testing my Angular application. I need to make an HTTP call on a local file, but the expects of the test are getting called before and after the HTTP call, causing it to crash. How can I resolve this issue? ...

Adding a script to the head of a Next.js page by using the Script component

I need assistance with inserting tracking code from Zoho application into the Head section of each page in my Next.js application. I am currently using a _document.tsx file and following the instructions provided by Next.js regarding the use of the Next.js ...

What is the best way to display an alert when the button is clicked repeatedly?

Is it possible to keep displaying the alert every time we click the button, rather than just once after clicking it? I currently have an alert set to trigger when a button is clicked, but it disappears after 3 seconds. How can I make it show up again with ...

Generate listview items containing anchor tags automatically

I am currently developing a web application using Jquery Mobile. After retrieving data from a webservice function, I am utilizing an ajax call to display this data on my webpage. $('[data-role=page]').on('pageshow', function () { var u ...

retrieve the coordinates of the northwest and southeast corners of a group of markers displayed on a Google Map

Is there a more efficient way to get the NE and SW corners of a set of markers on a Google map without iterating over each marker individually using JavaScript or Google functions? function fnSetBounds(){ var lowLat = 90; var highLat ...

Invoking a JavaScript function within an ASP Repeater

I am looking to incorporate a JavaScript function into an ASPX page within Visual Studios 2012. This function is designed to retrieve 7 values from a database multiple times and dynamically adjust the CSS based on these values. Additionally, it targets a s ...

Issue: The error message "articales.forEach is not a function" is indicating

app.get('/', (req, res) => { const articales = { title: 'Test Articles', createdAt: Date.now(), description: "Test Description" } res.render('index', { articales : articales }) }) <div ...

Real-time update of quiz results based on varying factors

In my quiz, I have set up variables that start at 0 and increase based on certain conditions. One variable should increase when a question is answered correctly, while the other should increase when a question is answered incorrectly. If you answer a quest ...