问题描述
抱歉,我是初学者,我找不到如何在 angular 中获取 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" | "数" | "bigint" | "布尔值" | “符号” | “未定义” | “对象” | "function"' 和 '"password"' 没有重叠。ts(2367) 任何建议将不胜感激
解决方法
您必须像这样在输入上添加模板引用
<input #someInput ...
然后使用 @ViewChild
注释引用 TypeScript 文件中的输入:
@ViewChild('someInput') input: ElementRef;
然后您就可以在代码中的任何位置检查输入的类型:
(this.input.nativeElement as HTMLInputElement).type === 'password';
如果您的问题是关于查询所有输入,则在所有输入上添加相同的模板引用,然后使用:
@ViewChildren('someInput') inputs!: QueryList<ElementRef>
,
您使用的方法是vanilla js的方法
在 angular 中,您应该使用表单模块,反应式表单将毫不费力地解决这个问题 要阅读 Angular 表单模块,请点击 here