Nick
Nick

Reputation: 27

Angular 2 Search

I'm trying to use a search box to filter a list of items using Angular 2 but when I type stuff into the search box it never fires the search method on the service. I know I'm probably missing something simple but any help would be much appreciated.

company.service.ts:

import { Injectable }    from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';

import 'rxjs/add/operator/toPromise';

import { CompanyModel } from './company';
import { CompaniesModel } from './company';

@Injectable()
export class CompanyService {

  private headers = new Headers({'Content-Type': 'application/json'});

  constructor(private http: Http) { }

  search(term: string): Observable<CompaniesModel> {
      console.log('search service', term);
      return this.http
          .get('/api/Company/Search/?search=' + term)
          .map((r: Response) => r.json().data as CompaniesModel);
  }
}

companies.component.ts:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { FormControl } from '@angular/forms';

import { CompanyModel } from './company';
import { CompaniesModel } from './company';
import { CompanyService } from './company.service';

@Component({
  moduleId: module.id,
  selector: 'companies-list',
  templateUrl: 'companies.component.html'
})
export class CompaniesComponent implements OnInit {
    companiesModel: Observable<CompaniesModel>;
    private searchTerms = new Subject<string>();

  constructor(
      private companyService: CompanyService,
    private router: Router) { }

  search(term: string): void {
      this.searchTerms.next(term);
  }

  ngOnInit(): void {
      this.companiesModel = this.searchTerms
          .debounceTime(300) 
          .distinctUntilChanged()
          .switchMap(term => this.companyService.search(term));

  }

  gotoDetail(company: CompanyModel): void {
      let link = ['/company', company.Id];
      this.router.navigate(link);
  }
}

companies.component.html

<h2>Companies</h2>
<div>
    <label>Search: </label>
    <input #searchBox id="search-box" (keyup)="search(searchBox.value)" />
</div>
<div>
    <button (click)="create()">
        Add
    </button>
</div>
<div *ngIf="companiesModel" class="grid grid-pad">
    <ul>
        <li *ngFor="let company of companiesModel.Companies | async" (click)="gotoDetail(company)">
            <div>
                <h4>{{company.Name}}</h4>
            </div>
        </li>
    </ul>
</div>

Upvotes: 0

Views: 8972

Answers (3)

Prashobh
Prashobh

Reputation: 9542

You can try the same using below code as well

 <input type="text" [(ngModel)]="queryString" id="search" placeholder="Search to type">

Pipe

@Pipe({
    name: 'FilterPipe',
})
export class FilterPipe implements PipeTransform {
    transform(value: any, input: string) {
        if (input) {
            input = input.toLowerCase();
            return value.filter(function (el: any) {
                return el.toLowerCase().indexOf(input) > -1;
            })
        }
        return value;
    }
}

You can modify the code as per your requirements.

Upvotes: 0

Angular2 searching without any custom pipes

<table>
 <thead>...</thead>
 <tbody>
       <tr *ngFor="let part of filterParts let i=index"></tr>
</tboby>

//code in component.ts file

 Partsfiltering(inputName){
       this.filterParts = [];
      if(inputName != ""){
            this.parts.forEach(element => {         
       if(element.partNumber.toUpperCase().indexOf(inputName.toUpperCase())>=0){
                  this.filterParts.push(element);
               }
            });
      }else{
         this.filterParts = this.parts;
      }
     }

Upvotes: 0

KwintenP
KwintenP

Reputation: 4775

You are never subscribing on the subject searchTerms. If you do not subscribe, the operators you've layed out will never be executed.

this.searchTerms
      .debounceTime(300) 
      .distinctUntilChanged()
      .switchMap(term => this.companyService.search(term))
      .subscribe((val) => //do something with the result here);

Example Jsbin. Add the subscribe statement to see the console logs. http://jsbin.com/zijuvet/edit?html,js,console

Upvotes: 1

Related Questions