Home > database >  Angular. Change type of input
Angular. Change type of input

Time:01-06

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:

<div  (click)="togglePasswords()">
    <i *ngIf="show_password"  aria-hidden="true"></i>
    <i *ngIf="!show_password"  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.

CodePudding user response:

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.

  • Related