Search code examples
angularinputangular6keyup

call function of other component on event in one component in Angular 6


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?


Solution

  • 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