【问题标题】:How do I find the type of an input in angular?如何找到角度输入的类型?
【发布时间】:2025-11-24 20:00:02
【问题描述】:

对不起,我是一个初学者,我找不到如何获得 input 角度类型。 这是我写的一段代码:

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");
 }

}

当我使用 typeof(x) 时,它给了我这个: 此条件将始终返回 'false',因为类型 '"string" | "数字" | “大整数” | “布尔” | “象征” | “未定义” | “对象” | "function"' 和 '"password"' 没有重叠。ts(2367) 任何建议将不胜感激

【问题讨论】:

  • 您需要添加更多代码。这有点不可读。
  • 您需要显示更多代码。例如,什么是 x?另外,你的意思是获取元素的类型,比如<input type='password' />
  • 对不起,我添加了我正在使用的完整功能,希望它现在更具可读性。另外,是的,我的意思是输入元素的类型(不是变量的类型,如 int、bool、string ......)

标签: javascript angularjs angular input input-type-range


【解决方案1】:

您必须像这样在输入上添加模板引用

<input #someInput ...

然后用@ViewChild注解引用TypeScript文件中的输入:

@ViewChild('someInput') input: ElementRef;

然后你就可以在代码中的任何地方检查输入的类型了:

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

如果您的问题是关于查询所有输入,则在所有输入上添加相同的模板引用,然后使用:

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

【讨论】:

  • 我试过这个,但不幸的是它对我不起作用。这是我在您提供的帮助下编写的代码: 在 HTML 中:code
    code 对于打字稿,我会在下一条评论中发布它,因为它太长了
  • 在打字稿中:code @ViewChild('passwordInput') 输入:ElementRef; passwordVisibilityToggle() { var passwordEye = document.getElementById("password-eye"); if ((this.input.nativeElement as HTMLInputElement).type === 'password') { (this.input.nativeElement as HTMLInputElement).type = "text"; passwordEye?.classList.remove("off"); passwordEye?.classList.add("on"); } else { (this.input.nativeElement as HTMLInputElement).type = "password"; passwordEye?.classList.remove("on"); passwordEye?.classList.add("off"); } } code
  • 您可以编辑您的答案,添加您的尝试和您遇到的错误吗?
【解决方案2】:

你使用的方法是vanilla js的方法

在 Angular 中,您应该使用表单模块,反应式表单会毫不费力地解决这个问题 要阅读角度形式模块,请单击here

【讨论】:

    最近更新 更多