I'm using Angular 6
.
I have a component HeaderComponent whose html contain an input field like
header.component.html
<form>
<input (keyup)="search($event)">
</form>
<app-search-result-card *ngIf="searchQuery.length > 3"
[searchQuery]="searchQuery">
</app-search-result-card>
SearchResultComponent has a function to perform search
export class SearchResultCardComponent implements OnInit {
@Input() searchQuery: string;
searching = true;
constructor(
private searchService: SearchService
) { }
ngOnInit() {
this.performSearch();
}
/**
* Perform search
*/
performSearch() {
this.searching = true;
console.log(this.searchQuery);
this.searching = false;
}
}
How can I call the function performSearch
on the change in searchQuery
value on keyup
in the input field?
Use
output
event binding for the sameInject
SearchResultCardComponent
toHeaderComponent
and call its functionperformSearch()
whensearchKey.length > 3
as below:In your
HeaderComponent.ts
,use binding in your form using ngModel directive
In Header Component make searchQuery as empty string
In your search component use lifecycle hook ngOnChanges to detect the input property changes or you can use propety setter. In ngOnChanges life cycle you will get searchQuery property value. In there you can perform search function
demo Link
header.component.ts
here how you can call child method in parent, but I suggest you refactor you component, make SearchResultCardComponent component dummy, receive only search result from parent.