using Angular 2.1.0 ... Я работаю над директивой, которая при применении к текстовым полям отображает «X» справа от текстового поля. При нажатии «X» при удалении следует удалить текст из текстового поля и очистите модель, аналогичную этому угловому репо https://github.com/amageed/angular-resetfield.Угловая атрибут атрибута 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);
}
}
Edit: эффект я после что-то вроде этого:
для повторного использования, я пытался создать директиву атрибута для обработки всего этого ролика вела.
Эта строка 'searchIcon.addEventListener ('нажмите', this.clearValue),' 'должны быть searchIcon.addEventListener (» click ',() => this.clearValue()); ' – admax