如何在Angular2上使用onBlur事件?

问题描述 投票:81回答:6

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

<input type="text">

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

javascript angular onblur
6个回答
177
投票

使用(eventName) for while绑定事件到DOM,基本上()用于事件绑定。还可以使用ngModel来获取myModel变量的双向绑定。

标记

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

export class AppComponent { 
  myModel: any;
  constructor(){
    this.myModel = '123';
  }
  onBlurMethod(){
   alert(this.myModel) 
  }
}

Demo

替代(不是优选的)

<input type="text" #input (blur)="onBlurMethod($event.target.value)">

Demo


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

ctrl = new FormControl('', {
   debounce: 1000, 
   updateOn: 'blur', //default will be change
   validators: [Validators.required]
}); 

Design Docs


9
投票

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

使用(eventName) for while绑定事件到DOM,基本上()用于事件绑定。你也可以使用ngModel为你的model获得双向绑定。在ngModel的帮助下,您可以在model中操纵component变量值。

在HTML文件中执行此操作

<input type="text" [(ngModel)]="model" (focusout)="someMethodWithFocusOutEvent($event)">

在您的(组件).ts文件中

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

6
投票

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

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

你会得到“结果”的输出


1
投票
/*for reich text editor */
  public options: Object = {
    charCounterCount: true,
    height: 300,
    inlineMode: false,
    toolbarFixed: false,
    fontFamilySelection: true,
    fontSizeSelection: true,
    paragraphFormatSelection: true,

    events: {
      'froalaEditor.blur': (e, editor) => { this.handleContentChange(editor.html.get()); }}

1
投票

这是关于Github回购的建议答案:

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

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

Github : feat(forms): add updateOn blur option to FormControls


1
投票

HTML

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

TS

removeSpaces(string) {
 let splitStr = string.split(' ').join('');
  return splitStr;
}
© www.soinside.com 2019 - 2024. All rights reserved.