Angular 模板绑定输入框值仅在鼠标移动时更新问题求助
问题原因与解决方案
根本原因
该现象是Angular变更检测机制的正常表现:
- 你直接通过模板引用变量
#helloInput读取原生DOM元素的value属性,Angular不会主动监听原生DOM属性的实时变化,只有当变更检测周期被触发时,才会重新校验模板中绑定的所有表达式、更新视图 - 移动鼠标时触发的
mousemove事件默认被Zone.js捕获,会主动触发Angular的变更检测,所以此时才会更新模板中的插值内容和*ngIf的判断结果 - 输入内容时没有触发变更检测,通常对应两种场景:要么项目配置了禁用/部分禁用Zone.js,要么该输入框的输入事件没有被Zone.js正常捕获(比如输入框是第三方非Angular组件渲染的内容)
修复方案
方案1:绑定ngModel(推荐)
使用Angular模板驱动表单的ngModel指令,它会自动处理输入事件的变更检测触发,无需额外配置(注意需要在对应模块中导入FormsModule才能使用ngModel,同时要在组件类中定义对应的helloValue属性):
<input class="form-control" type="text" placeholder="hello there..." [(ngModel)]="helloValue" > {{helloValue}} <button class="btn btn-success" *ngIf="helloValue" >Show me</button>
方案2:手动绑定input事件触发变更检测
不想引入表单模块的话,只需要给input绑定一个空的input事件,Zone.js捕获到事件后就会自动触发变更检测:
<input class="form-control" type="text" placeholder="hello there..." #helloInput (input)="0" > {{helloInput.value}} <button class="btn btn-success" *ngIf="helloInput.value" >Show me</button>
方案3:手动触发变更检测
如果项目确实禁用了Zone.js,可以注入ChangeDetectorRef手动触发检测:
// 组件类中引入注入 import { ChangeDetectorRef, Component } from '@angular/core'; @Component({/* 组件基础配置 */}) export class DemoComponent { constructor(private cdr: ChangeDetectorRef) {} triggerCheck() { this.cdr.detectChanges(); } }
<input class="form-control" type="text" placeholder="hello there..." #helloInput (input)="triggerCheck()" >
内容的提问来源于stack exchange,提问作者Atlas91
相关产品推荐
相关产品推荐

