1
votes

When I use this in my template:

<select [(ngModel)]="selectedCompany" class="form-control">
    <option *ngFor="let company of companies" [ngValue]="company">{{company.Name}}</option>
</select>
{{selectedCompany}}

Value of {{selectedCompany}} is [object Object]. However, when I try to get Name property of selectedCompany like this:

{{selectedCompany.Name}}

I get the following error:

EXCEPTION: Uncaught (in promise): Error: Error in ./HomeComponent class HomeComponent - inline template:60:10 caused by: Cannot read property 'Name' of undefined

I am trying to figure out why am I getting that error. I think the property is there because {{company.Name}} works.

1

1 Answers

1
votes

That's because selectedCompany is not defined at the moment of template rendering. You have two solutions:

  1. Use safe navigation operator (?) to "protect" your template until selectedCompany is populated with data:

    {{selectedCompany?.Name}}
    
  2. Initialize selectedCompany variable in your component:

    selectedCompany = {};
    

Either of these will solve the problem.