ERROR TypeError: Cannot read property 'length' of undefined

Char picture Char · Jun 22, 2017 · Viewed 75.2k times · Source

There is an error in this part of my code

<img src="../../../assets/gms-logo.png" alt="logo" routerLink="/overview" alt="website icon">

But when I checked the assets folder, gms-logo.png is still there and in angular-cli.json, assets is also there. The path is also correct.

Recently though, I've been working on Search function. So my hypothesis is,

Has the program started searching even if the user is still not focused on the input type? How do I fix this?

Below is my html for Search and the showing of its suggestion segment

<input type="text" placeholder="Search" (keyup)="onSearch($event.target.value)">        
<div class="suggestion"  *ngIf="results.length > 0">
     <div *ngFor="let result of results ">
          <a href="" target="_blank">
                {{ result.name }}
          </a>
     </div>
</div>

Below is my component

results: Object;



 onSearch(name) {
            this.search
            .searchEmployee(name)
            .subscribe(
                name => this.results = name,//alert(searchName),this.route.navigate(['/information/employees/']),
                error => alert(error),
                );
}

Answer

Levi Fuller picture Levi Fuller · Jun 22, 2017

You need to initialize your results variable as an array.

In your component, add:

results = [];

Another option is to change your suggestion div's *ngIf statement to check if results is defined:

<div class="suggestion"  *ngIf="results">
   <div *ngFor="let result of results ">
          <a href="" target="_blank">
                {{ result.name }}
       </a>
   </div>
</div>