使用angular 2的HTML5事件处理(onfocus和onfocusout) [英] HTML5 event handling(onfocus and onfocusout) using angular 2

查看:275
本文介绍了使用angular 2的HTML5事件处理(onfocus和onfocusout)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个日期字段,默认情况下要删除占位符.

I have a date field and I want to remove the place holder by default.

我正在使用JavaScript onfocusonfocusout事件删除占位符.

I am using javascript onfocus and onfocusout events for removing placeholder.

有人可以帮助使用angular2指令吗?

Can anyone help with using angular2 directive?

<input name="date" type="text" onfocus="(this.type='date')" onfocusout="(this.type='text')" class="dateinput">

我尝试以这种方式解决,但是在重置输入字段类型时遇到问题.

I try to solving in this way, but i am getting problem with resetting the input field type.

import { Directive, ElementRef, Input } from 'angular2/core';
@Directive({
    selector: '.dateinput', 
    host: {
    '(focus)': 'setInputFocus()',
    '(focusout)': 'setInputFocusOut()',
  }})

  export class MyDirective {
      constructor(el: ElementRef) { this.el = el.nativeElement; console.log(this.el);}

      setInputFocus(): void {
        //console.log(this.elementRef.nativeElement.value);
      }
  }

推荐答案

尝试使用(focus)(focusout)代替onfocusonfocusout

像这样:-

<input name="date" type="text" (focus)="focusFunction()" (focusout)="focusOutFunction()">

您也可以这样使用:-

有些人更喜欢前缀前缀的替代形式,即规范形式:

some people prefer the on- prefix alternative, known as the canonical form:

<input name="date" type="text" on-focus="focusFunction()" on-focusout="focusOutFunction()">

了解有关事件绑定的更多信息请参见此处.

Know more about event binding see here.

您必须在使用案例中使用HostListner

you have to use HostListner for your use case

当主机元素发出指定事件时,Angular将调用修饰的方法.@HostListener是回调/事件处理程序方法的修饰器

Angular will invoke the decorated method when the host element emits the specified event.@HostListener is a decorator for the callback/event handler method

请参阅我的更新正常工作插件.

See my Update working Plunker.

工作示例 工作柱塞

Working Example Working Plunker

某些其他事件也可以用于角度-

Some other events can be used in angular -

(focus)="myMethod()"
(blur)="myMethod()" 
(submit)="myMethod()"  
(scroll)="myMethod()"

这篇关于使用angular 2的HTML5事件处理(onfocus和onfocusout)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆