Home > Software design >  core.mjs:6484 ERROR TypeError: Cannot read properties of undefined (reading 'name')
core.mjs:6484 ERROR TypeError: Cannot read properties of undefined (reading 'name')

Time:05-06

In the console.log, I have an error message but I cannot solve this problem...

Here is the error message

core.mjs:6484 ERROR TypeError: Cannot read properties of undefined (reading 'name')

enter image description here

How should I declare name below?

 ...
    <ng-container *ngIf="dta && dta.PP">
 ...

HTML

<ng-container *ngIf="dta && dta.PP  ">
  <div  style="width: 60%">
    <div >
      <div >
        <div >
          <table >
            <tbody>
              <tr>
                <th>Year</th>
                <td>{{ fiscalYear }}</td>
              </tr>
              <tr>
                <th>Country</th>
                <td>{{ selectedCountry.name }}</td>
              </tr>
              <tr>
                <th>Register</th>
                <td>{{ registreNational }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</ng-container>

TS

selectedCountry: Country;

ngOnInit(): void {
    ...

    this.service.getPaysDta().pipe(
        takeUntil(this.unsubscribe$)
    ).subscribe((countries) => {
        this.countries = countries;

        let selectedCountry = this.countries.find(c => c.id == this.country);
        if (selectedCountry) {
            this.selectedCountry = selectedCountry;
        }
    });

}

Country.ts

export class Country {
    id : string;
    name: string;

}

I don't know how to correctly declare the variable name... :S

Thank you for your help.

CodePudding user response:

The selectedCountry is undefined by default, it only gets assigned a value in the asynchronous getPaysDta() subscribe callback.

In the HTML you string interpolate {{ selectedCountry.name }}. Initially it will try to access the name property of undefined, hence the error message.

You can fix this very easily, by wrapping the string interpolation with an *ngIf.

Example:

<td>
<span *ngIf="selectedCountry">{{ selectedCountry.name }}</span>
</td>
  • Related