我试图在我的角度项目中应用自动完成功能,但它不起作用。
这里是代码 -
<!-- Start ignoring BootLintBear -->
<form class="navbar-form navbar-left">
<!-- Stop ignoring BootLintBear -->
<div class="input-group" id="nav-group">
<input #input type="text" name="query" class="form-control" id="nav-input" (keyup)="onquery($event)"
[(ngModel)]="searchdata.query">
<div id="output"></div>
<script>
function suggestMe(data) {
document.getElementById('output').innerHTML = data;
}
var storeData = '';
document.getElementById('nav-input').onkeyup = function() {
if(storeData!== ''){
document.body.removeChild(storeData);
}
var textBox = document.getElementById('nav-input').value;
storeData = document.createElement('script');
storeData.src = 'http://en.wikipedia.org/w/api.php?action=opensearch&limit=10&format=json&callback=suggestMe&search=' + textBox;
document.body.appendChild(storeData);
};
</script>
<div class="input-group-btn">
<button class="btn btn-default" id="nav-button" type="submit" (click)="submit()">
<i class="glyphicon glyphicon-search"></i>
</button>
</div>
</div>
</form>
欢迎提出建议:)
答案 0 :(得分:4)
不是将纯JavaScript与Typescript混合,为什么不在完整的Typescript中呢?尝试这种方式或根据您的需要进行调整。首先设置一个可观察的流
data: Observable<any>;
private searchTerms = new Subject<string>();
onquery(term: string): void {
this.searchTerms.next(term);
}
接下来,设置搜索功能
ngOnInit(): void {
this.data = this.searchTerms
.debounceTime(300) // pause in events
.distinctUntilChanged() // ignore if search term not changed
.switchMap(term => term // switch to new observable each time
//http service to retrieve your data
? this.searchService.search(term)
: Observable.of<any>([])
)
.catch(error => {
console.log(error);
});
}
模板:
<input #input type="text" name="query" class="form-control" id="nav-input" (keyup)="onquery(input.value)">
<div id="output">
<div *ngFor="let item of (data | async)">{{ item }}</div>
</div>