简体   繁体   English

如何在 angular 中找到输入的类型?

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

Sorry I'm a beginner and I can't find how to get the input type in angular.抱歉,我是初学者,在 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" |当我使用 typeof(x) 时,它给了我这个:这个条件总是返回 'false',因为类型 '"string" | "number" | "数字" | "bigint" | “大整数” | "boolean" | “布尔” | "symbol" | “象征” | "undefined" | “未定义” | "object" | “对象” | "function"' and '"password"' have no overlap.ts(2367) Any advice would be appreciated “功能”和“密码”没有重叠。ts(2367)任何建议将不胜感激

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注释引用 TypeScript 文件中的输入:

@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>

The method you used is that of vanilla js你使用的方法是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 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM