如何在Angular2上使用onBlur事件?

Ign*_*nat 95 javascript onblur angular

你如何在Angular2中检测到onBlur事件?我想用它

<input type="text">
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮我理解如何使用它吗?

Pan*_*kar 189

使用(eventName)的同时,结合事件,DOM,主要()用于事件绑定.还用于ngModel获取myModel变量的双向绑定.

标记

<input type="text" [(ngModel)]="myModel" (blur)="onBlurMethod()">
Run Code Online (Sandbox Code Playgroud)

export class AppComponent { 
  myModel: any;
  constructor(){
    this.myModel = '123';
  }
  onBlurMethod(){
   alert(this.myModel) 
  }
}
Run Code Online (Sandbox Code Playgroud)

演示

替代(不是优选的)

<input type="text" #input (blur)="onBlurMethod($event.target.value)">
Run Code Online (Sandbox Code Playgroud)

演示


对于模型驱动的表单来激活验证blur,您可以传递updateOn参数.

ctrl = new FormControl('', {
   updateOn: 'blur', //default will be change
   validators: [Validators.required]
}); 
Run Code Online (Sandbox Code Playgroud)

设计文档

  • 为什么替代方案不受欢迎? (2认同)

Ani*_*ale 11

你也可以使用(focusout)事件.

<input type="text" [(ngModel)]="model" (focusout)="someMethodWithFocusOutEvent($event)">
Run Code Online (Sandbox Code Playgroud)

并在ts文件中

export class AppComponent { 
 model: any;
 constructor(){ }
 someMethodWithFocusOutEvent(){
   console.log('Your method called');
   // Do something here
 }
}
Run Code Online (Sandbox Code Playgroud)


Cha*_*ary 6

您可以在输入标签中直接使用(模糊)事件.

<div>
   <input [value] = "" (blur) = "result = $event.target.value" placeholder="Type Something">
   {{result}}
</div>
Run Code Online (Sandbox Code Playgroud)

你会得到" 结果 "的输出