尝试实现一个可重用的搜索框。
代码很基础,我对 Angular 2 还比较陌生,但现在已经使用 Angular 1 一段时间了。
为什么文本框焦点上的值没有清除?
import { Component, OnInit, Input } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'searchbox',
template: `
<form id="search" action="/search" method="get" [class.focus]="focus" class="searchbar" autocomplete="off" role="search">
<i class="fa fa-search search-icon"></i>
<input (focus)="onFocus()" (focusout)="onFocusOut()" name="q"
type="text" [value]="value" [placeholder]="placeholder" tabindex="1" autocomplete="off" maxlength="240">
<button type="submit" class="btn js-search-submit">
<i class="fa fa-search"></i>
</button>
</form>
`,
styleUrls: [
'./searchbox.component.less'
]
})
export class SearchBoxComponent implements OnInit {
@Input() placeholder: string;
@Input() value: string;
focus: boolean;
ngOnInit() { }
onFocus() {
this.value = '';
console.log(this.value);
this.focus = true;
}
onFocusOut() {
console.log('focus out');
this.focus = false;
}
}
最佳答案
您需要使用 [(ngModel)] 而不是 @Input() 进行双向数据绑定(bind)。
<input (focus)="onFocus()" (focusout)="onFocusOut()" name="q"
type="text" [(ngModel)]="value" [placeholder]="placeholder" tabindex="1" autocomplete="off" maxlength="240">
export class SearchBoxComponent implements OnInit {
@Input() placeholder: string;
value: string;
focus: boolean;
ngOnInit() { }
onFocus() {
this.value = null;
console.log(this.value);
this.focus = true;
}
onFocusOut() {
console.log('focus out');
this.focus = false;
}
}
希望对你有帮助!!
关于javascript - 清除 Angular 2 中的文本框不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43817141/