How do I find the type of an input in angular?

2.6k Views Asked by At

Sorry I'm a beginner and I can't find how to get the input type in angular. This is the piece of code i have written:

passwordVisibilityToggle() {

var x = document.getElementById("password");
var passwordEye = document.getElementById("password-eye");

if (x.type === 'password') {
  x.type = "text";
  passwordEye?.classList.remove("off");
  passwordEye?.classList.add("on");
 } else {
   x.type = "password";
   passwordEye?.classList.remove("on");
  passwordEye?.classList.add("off");
 }

}

When I use typeof(x) it gives me this: This condition will always return 'false' since the types '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"password"' have no overlap.ts(2367) Any advice would be appreciated

2

There are 2 best solutions below

3
On

You have to add a template reference on the input like this

<input #someInput ...

Then reference the input in the TypeScript file with the @ViewChild annotation:

@ViewChild('someInput') input: ElementRef;

Then you'll be able to check the type of the input anywhere in the code with this:

(this.input.nativeElement as HTMLInputElement).type === 'password';

If your question is about querying all of the inputs then add the same template reference on all of them, then use:

@ViewChildren('someInput') inputs!: QueryList<ElementRef>
0
On

The method you used is that of vanilla js

In angular you should use the forms module reactive forms will carter for this with little effort To read on angular forms module click here