Search code examples
angulartypescripttypeerrorundefined-function

Angular 5 typeerror:


I am using Angular 5 in a project and i get a typescript error:

ERROR TypeError: Cannot read property 'indexOf' of undefined

What my code is supposed to do is to update the template on input change like this:

The template:

<input #f (input)="filterResults(f.value)"/>

<div *ngIf="filteredCandidates.length">
    <ul class="filtered-candidates-list">
        <li *ngFor="let candidate of filteredCandidates">
            {{ candidate.name }}
        </li>
    </ul>
</div>

And the component.ts:

  private queryString: string;
  private candidates: Candidate[] = []
  private filteredCandidates: Candidate[] = [];

  filterResults(queryString) {
    this.candidatesService.filterCandidates().subscribe(candidates => this.candidates = candidates);
    if (!queryString) {
      return;
    }
    else {
      this.candidates.filter(c => { c.name.indexOf(queryString) >= 0 });
    }
  }

I tried using the method .contains() on the c.name, and got the same result. The typeof candidate.name is still string, as expected, as well as the input which is also a string. However, it is like i can't use the string methods just due to typescript being incorporated.


Solution

  • If c.name is not defined in some cases, you could do the check like this:

      this.candidates.filter(c => { 
          return c.name !== null && c.name.indexOf(queryString) >= 0 
      });
    

    Here, !== null will check for both null and undefined values.