我有一个日期字段,我想默认删除占位符。
我正在使用javascript onfocus 和 onfocusout 事件来移除占位符。
任何人都可以使用angular2指令吗?
<input name="date" type="text" onfocus="(this.type='date')" onfocusout="(this.type='text')" class="dateinput">
我尝试以这种方式解决,但是我遇到了重置输入字段类型的问题。
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);
}
}
答案 0 :(得分:170)
尝试使用(focus)
和(focusout)
代替onfocus
和onfocusout
<input name="date" type="text" (focus)="focusFunction()" (focusout)="focusOutFunction()">
你也可以这样使用: -
有些人更喜欢on-prefix替代方案,称为规范形式:
<input name="date" type="text" on-focus="focusFunction()" on-focusout="focusOutFunction()">
了解有关事件绑定的更多信息see here。
您必须将HostListner用于您的用例
当host元素发出指定的事件时,Angular将调用trim方法。
@HostListener
是回调/事件处理程序方法的装饰器
请参阅我的更新工作Plunker。
工作示例 Working Plunker
答案 1 :(得分:4)
如果要动态捕捉组件上每个输入的焦点事件:
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');
});
});
}
}
答案 2 :(得分:0)
解决方案是这样的:
var filteredObjects = []
func filterObjects() {
filteredObjects = timeline?.postObjects?.filter{!($0.hidden ?? false)}
}
// Returning only the number of visible cells
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredObjects.count
}
// And creating cells for only visible rows
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let post = filteredObjects[indexPath.row] {
return (tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell).with(post: post, timelineController: self, darkMode: isDarkMode())
}
}
答案 3 :(得分:0)
我创建了一个与tabindex属性绑定的小指令。它会动态添加/删除has-focus类。
@Directive({
selector: "[tabindex]"
})
export class TabindexDirective {
constructor(private elementHost: ElementRef) {}
@HostListener("focus")
setInputFocus(): void {
this.elementHost.nativeElement.classList.add("has-focus");
}
@HostListener("blur")
setInputFocusOut(): void {
this.elementHost.nativeElement.classList.remove("has-focus");
}
}
答案 4 :(得分:0)
<input name="date" type="text" (focus)="focusFunction()" (focusout)="focusOutFunction()">
从Pardeep Jain为我工作