使用Angular 2.1.0 ... 我正在制定一个指令,当应用于文本框时,会显示一个" X"在文本框的右侧,这个" X"单击时,应删除文本框中的文本并清除模型,类似于angularjs repo https://github.com/amageed/angular-resetfield。
我的问题是我可以将输入值传递给指令但是我无法清除模型。现在在我的clearFunction上,我得到: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);
}
}
对于可重用性,我试图创建一个属性指令来处理这一切。
答案 0 :(得分:1)
如果你愿意,你可以做一些非常精细的事情,但是这个:
<input #searchBox id="search-box" placeholder="Search"/>
<button (click)="searchBox.value = null">
X
</button>