Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular. Change type of input

I have div, that, when pressed, triggers a function that change type of input.
There are two inputs, they have ‘password’ type, function, changes it to ‘text’

Problem
Error 1: ‘password’ is possibly ‘null’.
If i put <!> to the password field, there is new error: Property ‘type’ does not exist on type ‘Element’.

Html:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<div class="eyes" (click)="togglePasswords()">
    <i *ngIf="show_password" class="fa fa-eye" aria-hidden="true"></i>
    <i *ngIf="!show_password" class="fa fa-eye-slash" aria-hidden="true"></i>
</div>

TypeScript:

public togglePasswords(): void {
    let password = document.querySelector(".password");
    let repeat_password = document.querySelector(".repeat-password");

    this.show_password = !this.show_password;

    if (this.show_password) {
        password.type = "text";
        repeat_password.type = "text";
    }   else {
        password.type = "password"
        repeat_password.type = "password";
    }
}

I repeated it with a simple site (made index.html, put there script tag, in script.js repeated this), and it worked.

I inserted js code to tag inside html component in angular, but it didn’t help.

>Solution :

In your TypeScript code, the password and repeat_password variables are assigned the result of the document.querySelector function, which returns an HTMLElement object.

However, the type property is not a valid property of the HTMLElement object. Instead, you need to use the getAttribute and setAttribute methods to get and set the type attribute of the input elements.

Try this.

public togglePasswords(): void {
  let password = document.querySelector(".password");
  let repeat_password = document.querySelector(".repeat-password");

  this.show_password = !this.show_password;

  if (this.show_password) {
    password.setAttribute("type", "text");
    repeat_password.setAttribute("type", "text");
  } else {
    password.setAttribute("type", "password");
    repeat_password.setAttribute("type", "password");
  }
}

It should fix your error.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading