ERROR TypeError: Unable to read length of undefined property

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

it still exists and angular-cli.json

there are assets in it too. The path is also correct.

I recently worked on a search function. So my hypothesis:

Did the program start the search even if the user is still not focused on the input type? How to fix it?

Below is my html for search and showing its offer 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),
                );
}

      

+5


source to share


4 answers


You need to initialize the variable results

as an array.

In your component add:

results = [];

      



Another option is to change the clause of the div *ngIf

to check if it is defined results

:

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

      

+9


source


Safe navigation operator (?.) And null property paths

The safe corner navigation operator (?.) Is a convenient and convenient way to protect against null and null values ​​in property paths. Here it is, protecting against rendering the view from failing if currentHero is null.



So in your example, you can also use the safe navigation operator (?.):

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

      

+3


source


You can simply initialize your array in a declaration:

    result: Array<any>;

      

if the style of the problem persists you should check for null in your method like:

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

            error => alert(error),
            );
}

      

0


source


Initializing an empty variable solved my problem.

 DoctorList: any[] = [];

      

0


source







All Articles