call function of other component on event in one c

2019-08-29 18:04发布

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?

4条回答
在下西门庆
2楼-- · 2019-08-29 18:15

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楼-- · 2019-08-29 18:15

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);
}
查看更多
贪生不怕死
4楼-- · 2019-08-29 18:16

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

查看更多
Rolldiameter
5楼-- · 2019-08-29 18:22

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.

查看更多
登录 后发表回答