Javascript 如何在Angular2上使用onBlur事件?

Javascript 如何在Angular2上使用onBlur事件?,javascript,angular,onblur,Javascript,Angular,Onblur,如何在Angular2中检测onBlur事件? 我想和你一起用 <input type="text"> 有人能帮我理解如何使用它吗?使用(eventName)因为在将事件绑定到DOM时,基本上()用于事件绑定。还可以使用ngModel获取myModel变量的双向绑定 标记 <input type="text" [(ngModel)]="myModel" (blur)="onBlurMethod()"> 备选方案(不可取) 这是Github回购协议的建议答案: /

如何在Angular2中检测onBlur事件? 我想和你一起用

<input type="text">

有人能帮我理解如何使用它吗?

使用
(eventName)
因为在将事件绑定到DOM时,基本上
()
用于事件绑定。还可以使用
ngModel
获取
myModel
变量的双向绑定

标记

<input type="text" [(ngModel)]="myModel" (blur)="onBlurMethod()">

备选方案(不可取)


这是Github回购协议的建议答案:

// example without validators
const c = new FormControl('', { updateOn: 'blur' });

// example with validators
const c= new FormControl('', {
   validators: Validators.required,
   updateOn: 'blur'
});

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

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

{{result}}
您将在“结果”中获得输出。

您也可以使用(focusout)事件:

使用
(eventName)
将事件绑定到DOM时,基本上
()
用于事件绑定。您还可以使用
ngModel
为您的
模型
获取双向绑定。在
ngModel
的帮助下,您可以在
组件中操作
model
变量值

在HTML文件中执行此操作

export class AppComponent { 
  myModel: any;
  constructor(){
    this.myModel = '123';
  }
  onBlurMethod(){
   alert(this.myModel) 
  }
}
<input type="text" [(ngModel)]="model" (focusout)="someMethodWithFocusOutEvent($event)">
export class AppComponent { 
 model: any;
 constructor(){ }
 someMethodWithFocusOutEvent(){
   console.log('Your method called');
   // Do something here
 }
}
HTML

<input name="email" placeholder="Email"  (blur)="$event.target.value=removeSpaces($event.target.value)" value="">

试着使用(focusout)而不是(blur)

为什么这个替代方案不可取?Angular不希望您使用HTML中的$event发送回JS。所有DOM操作都应该通过绑定、ngModel等方式完成。@Aniketkale如果我在你的方法
someMethodWithFocusOutEvent
中添加一个警报,当警报使字段失去焦点时,程序进入一个循环,有没有办法解决这个问题?
<input type="text" [(ngModel)]="model" (focusout)="someMethodWithFocusOutEvent($event)">
export class AppComponent { 
 model: any;
 constructor(){ }
 someMethodWithFocusOutEvent(){
   console.log('Your method called');
   // Do something here
 }
}
<input name="email" placeholder="Email"  (blur)="$event.target.value=removeSpaces($event.target.value)" value="">
removeSpaces(string) {
 let splitStr = string.split(' ').join('');
  return splitStr;
}