使用Angular 2.1.0 ... 我正在处理一个指令,该指令应用于文本框时显示文本框右侧的“X”,单击时此“X”应从文本框中删除文本,清除模型,类似于这个angularjs回购https://github.com/amageed/angular-resetfield。Angular 2属性指令清除文本框?
我的问题是我可以将输入值传递给指令,但我无法清除模型。现在在我的清除功能我得到:TypeError: Cannot read property 'emit' of undefined
我承认,我可能会在这个完全错误的方法,我愿意接受任何建议。
下面是我原本计划在HTML中使用它:
<input type="text" placeholder="Search" [(ngModel)]="filterText" [(inputClear)]="filterText">
这里是我的指令:
@Directive({
/* tslint:disable */
selector: '[inputClear]',
exportAs: 'inputClear'
})
export class inputClearDirective implements OnInit, OnChanges {
@Input() inputClear: any;
@Output() inputClearChange = new EventEmitter();
constructor(private renderer: Renderer, private el: ElementRef) {
}
ngOnChanges(change) {
console.log('val', this.inputClear);
if (this.inputClear) {
console.log('show');
this.showElement();
}
if (!this.inputClear) {
this.hideElement();
console.log('hide');
}
}
//on Init add x to text box
ngOnInit() {
let me = this.el.nativeElement as HTMLInputElement;
if (me.nodeName.toUpperCase() !== 'INPUT') {
throw new Error('Invalid input type for clearableInput:' + me);
}
let wrapper = document.createElement('span') as HTMLSpanElement;
let searchIcon = document.createElement('i') as HTMLElement;
searchIcon.id = 'searchIcon';
// // calls the clearvalue function
searchIcon.addEventListener('click', this.clearValue);
////clears the textbox but not the model
// searchIcon.addEventListener('click', function() {
// console.log('clicked');
// let inp = this.parentElement.previousSibling as HTMLInputElement;
// if (inp && inp.value.length) {
// inp.value = '';
// }
// });
wrapper.setAttribute('style', 'margin-left: -37px;position: relative; margin-right:37px;');
searchIcon.setAttribute('style', 'display:none');
searchIcon.className = 'fa fa-times fa-1x';
wrapper.appendChild(searchIcon);
wrapper.id = 'searchSpan';
me.insertAdjacentElement('afterend', wrapper);
}
showElement() {
let searchIcon = document.getElementById('searchIcon');
if (searchIcon) {
searchIcon.removeAttribute('style');
}
}
hideElement() {
let searchIcon = document.getElementById('searchIcon');
if (searchIcon) {
searchIcon.setAttribute('style', 'display:none');
}
}
clearValue() {
console.log('clicked');
this.inputClear = '';
this.inputClearChange.emit(this.inputClear);
}
}
for re-usability,我试图创建一个属性指令来处理这个所有rol导致了。
此行'searchIcon.addEventListener( '点击',this.clearValue);'应该是'searchIcon.addEventListener(”点击',()=> this.clearValue());' – admax