【问题标题】:How to detect input field value changes in angular with each value insertion?如何检测每次值插入时输入字段值的角度变化?
【发布时间】:2023-01-13 15:50:37
【问题描述】:

如何在不按角度输入按钮的情况下立即检测输入字段值的变化?

我试图在 Angular 中输入字段的值更改时触发一个函数。最初我使用 Keypress 事件,它正确地检测到输入字段的插入,但即使我使用退格键从值中删除任何字符,它也没有触发该功能,这意味着这些更改没有被注意到。我期待它会在每次更改或更新值时触发该事件。

【问题讨论】:

  • 你能提供一些代码或 stackblitz 吗?
  • 例如,看下面的代码 sn-p。它只检测插入,不检测退格删除。 <mat-form-field class="example-full-width"> <mat-label>Search</mat-label> <input matInput placeholder="Word" [(ngModel)]="search" (keypress)="filterTbl()" matTooltip="Filter Result"> </mat-form-field>
  • <input matInput placeholder="Word" [(ngModel)]="search" (keypress)="filterTbl()" matTooltip="过滤结果">

标签: javascript angular angularjs-directive event-handling web-frontend


【解决方案1】:

在 HTML 中

<input (input)="type($event)" type="text" />

在TS

 type(event) {
    console.log(event.target.value);
  }

演示链接:- Link

【讨论】:

  • 使用[(ngModel)] 是更“有角度的方式”。这种“双向绑定”允许为 .ts 中声明的变量赋值
【解决方案2】:

你可以使用 [(ngModel)]。我建议你“拆分”“香蕉语法”

<input matInput placeholder="Word" 
          [ngModel]="search" 
          (ngModelChange)="search=$event;doSomething($event)">

doSomething(value:string)
{
    console.log(value)
}

另一种方法可以是

<!--see that the event "input" return a "generic event"
    so you use $event.target.value to "reach" the value-->
<input matInput placeholder="Word" 
          [(ngModel)]="search" 
          (input)="doSomething($event.target.value)">

或者

<input matInput placeholder="Word" 
          [(ngModel)]="search" 
          (ngModelChange)="doSomething($event)">

【讨论】:

    猜你喜欢
    • 2020-04-11
    • 2017-08-24
    • 2017-01-08
    • 2011-09-25
    • 1970-01-01
    • 1970-01-01
    • 2020-07-24
    • 2018-06-13
    • 1970-01-01
    相关资源
    最近更新 更多