angular - 更改事件未触发
问题描述
我有一种情况,文本框可能会更改,但不是由用户输入引起的,我需要检测这种更改。输入定义如下:
<input type="text" (change)="onChange($event)" >
在 .ts 我有 onChange 方法:
onChange(event:any){
// something todo here
}
据我了解,这应该在 Angular 9 中工作,但事件没有触发。我错过了什么?
解决方案
问题
以编程方式更改值不会触发change
事件。
发出你自己的事件
Event
您可以使用Event API创建自己的。您将需要访问将事件绑定到的节点(您可以使用ViewChild)
请参阅此 stackblitz 演示中的实时示例。
app.component.ts
import { Component, ViewChild } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
value = '';
@ViewChild('input') input;
onChange(event:any){
alert('change event triggered');
}
changeValue() {
this.value = 'Value set';
// also trigger an event on the input.
let event = new Event('change');
this.input.nativeElement.dispatchEvent(event);
}
}
app.component.html
<input #input type="text" (change)="onChange($event)" [value]='value'>
<button (click)='changeValue()'>Change</button>;
或者
或者,您可以采用另一种方式,并在以onChange
编程方式更改值后直接运行方法中的代码。请注意,您可能需要重构代码以免依赖于发出的$event
.
推荐阅读
- android - OpenGL渲染器:戴维
- php - php会话使用分页自动增加会话值
- typescript - 我需要用类型替换签名中的原语吗?
- json - 如何重置 Visual Studio Code 的默认所有 json 设置?
- html - 如何在图像上叠加渐变
- java - 如何在后台运行代码或完整应用程序
- netlogo - Netlogo,在长度为 x 的列表中迭代 n 个项目(其中 n <= x)
- typescript - Typescript 中的类型定义中的方括号是什么意思?
- matlab - 为什么我不能在这里使用'scatter3'?
- javascript - 从用户输入自动创建 Javascript 表单