问题
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?
回答1:
use binding in your form using ngModel directive
<form>
<input type="text" [(ngModel)]="searchQuery" name="searchQuery">
</form>
<search [searchQuery]="searchQuery"></search>
In Header Component make searchQuery as empty string
searchQuery: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
export class SearchComponent implements OnChanges {
searching: boolean
@Input() searchQuery: string;
ngOnChanges(changes:SimpleChanges){
if(changes.searchQuery.currentValue.length > 3){
this.performSearch()
}
}
performSearch() {
this.searching = true;
console.log(this.searchQuery);
this.searching = false;
}
}
demo Link
回答2:
Use output
event binding for the same
<app-search-result-card *ngIf="searchQuery.length > 3"
[searchQuery]="searchQuery"
(queryResult)='queryResult($event)'>
</app-search-result-card>
回答3:
header.component.ts
// use ViewChild to get instance of SearchResultCardComponent in template
@ViewChild(SearchResultCardComponent) src: SearchResultCardComponent;
search(event) {
this.src.performSearch();
}
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.
回答4:
Inject SearchResultCardComponent
to HeaderComponent
and call its function performSearch()
when searchKey.length > 3
as below:
In your HeaderComponent.ts
,
constructor(private searchResultCardComponent: SearchResultCardComponent){}
search(searchKey: string) {
if(searchKey.length <= 3) return;
let searchResult = this.searchResultCardComponent.performSearch(searchKey);
}
来源:https://stackoverflow.com/questions/53827707/call-function-of-other-component-on-event-in-one-component-in-angular-6