Angular 2 属性指令清除文本框?

Angular 2 attribute directive to clear textbox?

使用 Angular 2.1.0... 我正在研究一个指令,当应用于文本框时,在文本框的右侧显示一个 "X",单击此 "X" 时,应该从文本框中删除文本并清除模型,类似于此angularjs 回购 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);
}
}

编辑:我想要的效果是这样的:

为了可重用性,我试图创建一个属性指令来处理这一切。

如果你愿意,你可以制作一些非常精致的东西,但是这个怎么样:

<input #searchBox id="search-box" placeholder="Search"/>
<button (click)="searchBox.value = null">
    X
</button>