Meik Vtune
Meik Vtune

Reputation: 490

Angular: Can't read property of undefined while json-pipe shows property

filter.ts

export interface Filter {
    id: number;
    name: string;
    tags: Array<Tag>;
}

tag.ts

export interface Tag {
    id: number;
    value: string;
}

filters.component.ts

export class FiltersComponent implements OnInit {
//Filter contains a list of tags
public filterList: Array<Filter>;
public selectedFilter: Filter;

constructor(private filterService: FiltersService) {
  this.filterList = new Array<Filter>();
}

ngOnInit() {
  this.filterService.getAllFilters().subscribe(filter => setTimeout(
    () => this.filterList.push(...filter), 2000
  ))
}

onSelect(f: Filter){
  if(f === this.selectedFilter){
    this.selectedFilter = null;
  }else{
    this.selectedFilter = f;
    console.log(this.selectedFilter);
  }
}
}

filters.component.html

  <div>
    <div class="left">
      <mat-list class="filter-list" *ngFor="let f of filterList"
                (click)="onSelect(f)">
        <span>
          {{f.id}}
        </span>
        <span>
          {{f.name}}
        </span>
      </mat-list>
    </div>
    <div class="right">
      <ng-container *ngIf="selectedFilter">
        {{selectedFilter | json}}
        <mat-list *ngFor="let tag of selectedFilter.tags"></mat-list>
        <span>
          {{tag.id}}
        </span>
        here
      </ng-container>

    </div>
  </div>

After that wall of code, here comes my problem:

I am trying to access the {{tag.id}} in the html. the console.log(...) shows me that the filter infact has atleast one tag, which is why the ngFor executes(not sure if that's the right word) the {{tag.id}}, however I'm still getting the following error:

ERROR TypeError: Cannot read property 'id' of undefined

Since I am already using the nfIf to check that there infact is a Filter and I am already using ngFor to check for tags, I have absolutely no idea what I am doing wrong.

If it matters, both Array<Filters> and Array<Tags> are json arrays(showing them in html requires the json-pipe)

Upvotes: 1

Views: 567

Answers (1)

SiddAjmera
SiddAjmera

Reputation: 39432

The issue is here:

<mat-list *ngFor="let tag of selectedFilter.tags"></mat-list>

Your mat-list ends here and the span where you're using tag.id is below that. Hence it's undefined.

Restructure your mat-list's end tag somehow to include the span inside the mat-list. Something like this:

<div>
  <div class="left">
    <mat-list class="filter-list" *ngFor="let f of filterList" (click)="onSelect(f)">
      <span>
          {{f.id}}
        </span>
      <span>
          {{f.name}}
        </span>
    </mat-list>
  </div>
  <div class="right">
    <ng-container *ngIf="selectedFilter">
      {{selectedFilter | json}}
      <mat-list *ngFor="let tag of selectedFilter.tags">
        <span>
          {{tag.id}}
        </span> here
      </mat-list>
    </ng-container>

  </div>
</div>

Upvotes: 2

Related Questions