我有一个日期字段,我想默认删除占位符.
我正在使用javascript onfocus和onfocusout事件来删除占位符.
任何人都可以帮助使用angular2指令吗?
<input name="date" type="text" onfocus="(this.type='date')" onfocusout="(this.type='text')" class="dateinput">
Run Code Online (Sandbox Code Playgroud)
我尝试以这种方式解决,但我遇到重置输入字段类型的问题.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
Par*_*ain 200
尝试使用(focus)
而(focusout)
不是onfocus
和onfocusout
像这样 : -
<input name="date" type="text" (focus)="focusFunction()" (focusout)="focusOutFunction()">
Run Code Online (Sandbox Code Playgroud)
你也可以像这样使用: -
有些人更喜欢on-prefix替代方案,称为规范形式:
<input name="date" type="text" on-focus="focusFunction()" on-focusout="focusOutFunction()">
Run Code Online (Sandbox Code Playgroud)
了解更多关于事件绑定在这里看到.
你必须使用HostListner作为你的用例
当host元素发出指定的事件时,Angular将调用trim方法.
@HostListener
是回调/事件处理程序方法的装饰器
请参阅我的更新工作Plunker.
工作实例 Working Plunker
如果要动态捕获焦点事件在组件的每个输入上:
import { AfterViewInit, Component, ElementRef } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
constructor(private el: ElementRef) {
}
ngAfterViewInit() {
// document.getElementsByTagName('input') : to gell all Docuement imputs
const inputList = [].slice.call((<HTMLElement>this.el.nativeElement).getElementsByTagName('input'));
inputList.forEach((input: HTMLElement) => {
input.addEventListener('focus', () => {
input.setAttribute('placeholder', 'focused');
});
input.addEventListener('blur', () => {
input.removeAttribute('placeholder');
});
});
}
}
Run Code Online (Sandbox Code Playgroud)
在此处签出完整代码:https : //stackblitz.com/edit/angular-93jdir