1
    <h1>{{title}}</h1>
<ul>
  <li *ngFor="let breed of data.message | keyvalue">
    <a [routerLink]="['/picsofbreed']" [queryParams]="{breed: breed.key}" target="_blank">{{breed.key}}</a> 
    <ul *ngIf="breed.value.length > 0">
    <!-- trying to only show list if breed.value is not empty--> 
      <li>{{breed.value}}</li>
      <!-- <li *ngFor="let sub of breed.value">{{sub}}</li> trying to iterate breed.value-->
    </ul>
  </li>
</ul>
<app-gallery></app-gallery>

I'm trying to iterate through dog sub breeds but only if the length is > 0. https://dog.ceo/dog-api/documentation/ click here for json body.

I am getting length not a property of unknown. Each breed has an empty array if there are no sub breed.

Component

    import { Component, OnInit } from '@angular/core';
import { DogbreedsService } from './dogbreeds.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-dogbreedlist',
  templateUrl: './dogbreedlist.component.html',
  styleUrls: ['./dogbreedlist.component.css']
})
export class DogbreedlistComponent implements OnInit {
  data: any; 
  
  title:string  = 'Dog Breeds and Subbreeds';
  constructor(private route: Router, private breedData: DogbreedsService){}
  ngOnInit() 
  {
    this.breedData.getBreeds().subscribe((result) => {
      this.data = result
    })
  }

}
Bryant Irawan
  • 79
  • 1
  • 6
  • 1
    Post your component class code, at least what to are using to populate `data` – wlf Aug 20 '22 at 08:45
  • 1
    I see nothing wrong in code. please explain what is your excepting. by the way I ran your code in stackblitz, it worked fine. see this [Example](https://stackblitz.com/edit/angular-ivy-etimbb?file=src/app/app.component.ts). – Exception Aug 20 '22 at 08:47
  • [ngIf]="!!data.length" – AhmadDeel Aug 20 '22 at 09:43
  • Try: *ngIf="breed.value?.length > 0" – Yoni A Aug 20 '22 at 19:14
  • Thanks everyone. Added the component. Yoni and AhmadDeel I tried that and still got an error. Also Exception, yeah I noticed it works. Perhaps it's how I got data. I used the subscribe method. – Bryant Irawan Aug 21 '22 at 18:29

1 Answers1

3

I recommend not trying to do this sort of thing in the template.

Instead, in the component, create the data structure that you actually want to display (e.g. remove the empty categories), and then just do a simple binding without the conditional logic.

GreyBeardedGeek
  • 29,460
  • 2
  • 47
  • 67
  • Thank you! this makes sense. I posted my component. Can you recommend a way for me to do that? Sorry I'm really new to angular. The above person didn't really define data in the class but I thought you needed to (this.data) and it's kind of confusing me. – Bryant Irawan Aug 21 '22 at 18:35
  • You can try filtering it, something like this: Object.entries(data.message).map( ([x, y]) => ({key:x, value:y}) ).filter(({key, value}) => value.length > 0) – GreyBeardedGeek Aug 22 '22 at 00:34