You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 10 表单输入框(change)事件仅失焦触发如何实现实时检测?

问题原因

change事件的原生触发逻辑就是仅在输入框失焦、或用户按下回车确认输入时才执行,Angular只是绑定了原生事件的默认逻辑,并不是你的写法有语法错误,只是事件选型不符合实时监听的需求。

解决方案

方案1:替换为input事件(最快适配现有代码)

直接把模板里的(change)替换为(input)即可,input事件会在每一次输入内容发生变化时实时触发:

<input type="text" (input)="check('test')" class="form-control form-control-lg form-control" formControlName="title" [ngClass]="!rForm.controls['title'].valid && rForm.controls['title'].touched ? 'red-border-class' : 'black-border-class'">

注:你原有代码写了两个重复的class属性,上面的示例已经帮你合并了。

方案2:订阅响应式表单的valueChanges(更符合Angular开发规范)

你当前使用了响应式表单(绑定了formControlName),可以直接在组件类中监听对应表单控件的数值变更流,不需要在模板中绑定事件:

import { Subscription } from 'rxjs';

export class YourComponent implements OnInit, OnDestroy {
  titleChangeSub: Subscription;

  ngOnInit() {
    // 订阅title控件的数值变更
    this.titleChangeSub = this.rForm.get('title').valueChanges.subscribe(() => {
      this.check('test');
    });
  }

  ngOnDestroy() {
    // 组件销毁时取消订阅,避免内存泄漏
    this.titleChangeSub?.unsubscribe();
  }
}

内容的提问来源于stack exchange,提问作者Ilyass

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 12:15:04