Pedro
Pedro

Reputation: 1178

Property throwing an undefined error in Angular

For some reason I keep getting the following error on various objects in my Angular 6 app:

TypeError: Cannot read property 'className' of undefined

Here is one of my components:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { InspectionService } from '@shared/services/inspection.service';
import { Inspection } from '@shared/models/inspection';

@Component({
  selector: 'app-inspection-detail',
  templateUrl: './inspection-detail.component.html',
  styleUrls: ['./inspection-detail.component.scss']
})
export class InspectionDetailComponent implements OnInit {

  inspection: Inspection = new Inspection();
  hiveStrength: any;
  feedPriority: any;
  varroaCount: any;

  constructor(private route: ActivatedRoute,
    private inspectionService: InspectionService,
    private router: Router) {
  }

  ngOnInit() {
    this.route.params.subscribe((params: Params) => {
      this.inspectionService.getInspection(params['id']).subscribe((response) => {
        this.inspection = response.data;
        this.hiveStrength = this.inspectionService.getHiveStrengthById(this.inspection.hive_strength);
        this.feedPriority = this.inspectionService.getFeedPriorityById(this.inspection.feed_priority);
        this.varroaCount = this.inspectionService.getVarroaCountById(this.inspection.varroa_count);
        console.log(this.hiveStrength);
      });
    });
  }
}

Relevant template part

<div class="row">
  <div class="col-sm-4">
    <small-stat [statClass]="hiveStrength.className" [iconClass]="'fas fa-heart'" [label]="'Hive Strength'" [value]="hiveStrength.name"></small-stat>
  </div>
  <div class="col-sm-4">
    <small-stat [statClass]="feedPriority.className" [iconClass]="'fas fa-tint'" [label]="'Feed Priority'" [value]="feedPriority.name"></small-stat>
  </div>
  <div class="col-sm-4">
    <small-stat [statClass]="varroaCount.className" [iconClass]="'fas fa-bug'" [label]="'Varroa Count'" [value]="varroaCount.name"></small-stat>
  </div>
</div>

Console log is returning the object in question and it is all displaying fine in the html template but the error keeps persisting.

Any ideas? I have a similar issue in another component on a different object so am wondering what I am doing wrong here...

Upvotes: 0

Views: 135

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222582

I think you should first check if data is defined when you print it in browser using safe navigation operator.

The Angular safe navigation operator (?.) is a fluent and convenient way to guard against null and undefined values in property paths.

 <div class="col-sm-4">
    <small-stat [statClass]="hiveStrength?.className" [iconClass]="'fas fa-heart'" [label]="'Hive Strength'" [value]="hiveStrength?.name"></small-stat>
  </div>

Upvotes: 1

Related Questions