首页 > 解决方案 > 更改事件未触发

问题描述

我有一种情况,文本框可能会更改,但不是由用户输入引起的,我需要检测这种更改。输入定义如下:

<input type="text" (change)="onChange($event)" >

在 .ts 我有 onChange 方法:

onChange(event:any){
  // something todo here
}

据我了解,这应该在 Angular 9 中工作,但事件没有触发。我错过了什么?

标签: angularangular9

解决方案


问题

以编程方式更改值不会触发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.


推荐阅读