我们一直面临将事件从 html 传递到需要它的 Javascript 方法之一的问题。
export class SearchComponent implements OnInit {
txtQueryChanged: Subject<string> = new Subject();
constructor(private AService: AService, public _router: Router, location: PlatformLocation) {
this.txtQueryChanged.debounceTime(1000)
.distinctUntilChanged()
.subscribe(model => {
this.q = model;
// Call function which calls API after a lag of 1 sec
this.getDetails(model);
});
}
watchChangesInSearchTerm(query: string, $event:
this.txtQueryChanged.next(query);
}
getDetails(event: any) {
this.eventKey = event.which;
if (this.q.trim() == "") {
this.closeSearch();
}
// other programming logic including the API call
}// end of function
}// end of class
现在调用这个 watchChangesInSearchTerm 的 HTML 如下
<input type="text" class="searchfield" [(ngModel)]="q" name="searchfield" (keyup)="watchChangesInSearchTerm(q, $event)" placeholder="What are you searching for today?">
现在来自 HTML 的代码调用 watchChangesInSearchTerm方法,但它只将 searchString 传递到参数中。watchChangesInSearchTerm依次对模型进行去抖动并调用getDetails方法。此方法也被许多其他用例调用,因此需要触发它的事件。
我们如何将事件传递给getDetails方法?