ERROR TypeError: Cannot read property 'length' of undefined

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>

The safe navigation operator ( ?. ) and null property paths

The Angular safe navigation operator (?.) is a fluent and convenient way to guard against null and undefined values in property paths. Here it is, protecting against a view render failure if the 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>

I got stuck in a similar situation where even after assigning results as an array ( as shown below ), the error persisted.

results: Array<any>;

Using '?' ( Safe Navigation Operator ) worked out well for me.

*ngIf="results?.length"

The Safe Navigation Operator (?) can be used to prevent Angular from throwing errors while trying to access the properties of an object that doesn't exist.

This example will evaluate the length only when a value of results is not Null or Undefined.


Initializing the variable to empty solved my issue.

 DoctorList: any[] = [];