【问题标题】:how to detect input type using Angular based on condition如何根据条件使用Angular检测输入类型
【发布时间】:2019-09-01 04:46:26
【问题描述】:

当我输入input值时,我想检测input的变化,如果input值等于我的条件,它将hide/showinput元素, 这是我尝试过的:

ts 文件

  isNoCard = false;

  onInputChange(inputValue: number): void {  
    if (inputValue === 7777) {
    this.isNoCard = true;
    }
 }

html 文件

<div *ngIf="!isNoCard">
<input (input)="onInputChange($event.target.value)" class="input--2" type="text" >
</div>

<div *ngIf="isNoCard">
<input class="input--1" type="text">
</div>

这是我的stackblitz 链接, 但是当我有条件时,它不起作用。有什么建议或指导可以解决这个问题吗?

【问题讨论】:

    标签: javascript html angular typescript input


    【解决方案1】:

    发生这种情况是因为从 HTML 传递的值是 string

    使用角度方式处理

    <div *ngIf="!isNoCard">
      <input  [(ngModel)]="data" (ngModelChange)="onInputChange(data)" class="input--2" type="number" >
    </div>
    

    Here is sample working stackblitz

    另外,请注意我已经创建了 type="number",因为您希望函数中的值是 number

    【讨论】:

      【解决方案2】:

      我认为您正在比较 inputValue 哪个类型的字符串与数字 7777。 即使您已将 inputValue 参数的类型指定为数字,但如果您尝试检查您会发现它是字符串的 typeof。

      console.log(typeof inputValue);
      

      在这种情况下,一个简单的解决方案是通过 + 运算符、parseInt 等技术将字符串转换为数字。

      如果我尝试遵循它的工作 -

      if (+inputValue === 7777) {
        this.isNoCard = true;
      }
      

      希望对你有所帮助。

      【讨论】:

        【解决方案3】:

        您已使用=== 运算符检查相等性,此处将返回false。 发生这种情况是因为输入值的类型为string,而7777number。 您可以对值进行类型转换,或者更简单的方法是使用 == 运算符。

        您可以简单地使用以下代码:

        onInputChange(inputValue: number): void {  
            if (inputValue == 7777) {
            this.isNoCard = true;
            }
        

        === 运算符检查值和类型,而== 运算符仅检查值。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-06-28
          • 2021-09-30
          • 1970-01-01
          • 1970-01-01
          • 2021-12-21
          • 2019-01-13
          • 1970-01-01
          相关资源
          最近更新 更多