Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Angular Component with Callback
export declare type QueryCallbackFunction = (results: string[]) => void;
declare type QueryFunction = (query: string, callback: QueryCallbackFunction) => void;
import {Component, Input} from '@angular/core';
@Component({
selector: 'app-example',
styleUrls: ['./example.component.scss'],
templateUrl: './example.component.html',
})
export class ExampleComponent {
/**
* Specify a Callback-Function which queries realtime results from a Server based on the entered Term.
* Usage example:
* <app-example
* …
* [queryFunction]="onQuery.bind(this)"
* ></app-example>
*
* onQuery(term: string, callback: QueryCallbackFunction): void {
* this.getResults(term).toPromise().then(results => {
* callback(results);
* });
* }
*/
@Input()
queryFunction: QueryFunction;
doSomething(term: string): void {
if (this.queryFunction) {
console.log('calling query function with', term);
this.queryFunction(term, (items) => {
console.log('query function returned', items);
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment