1
resposta

ERROR TypeError: Cannot read property 'length' of undefined

PhotosListComponent.html:13 ERROR TypeError: Cannot read property 'length' of undefined at PhotosComponent../src/app/photos/photos-list/photos/photos.component.ts.PhotosComponent.groupColumns (photos.component.ts:25) at PhotosComponent../src/app/photos/photos-list/photos/photos.component.ts.PhotosComponent.ngOnChanges (photos.component.ts:18) at checkAndUpdateDirectiveInline (core.js:9239) at checkAndUpdateNodeInline (core.js:10507) at checkAndUpdateNode (core.js:10469) at debugCheckAndUpdateNode (core.js:11102) at debugCheckDirectivesFn (core.js:11062) at Object.eval [as updateDirectives] (PhotosListComponent.html:13) at Object.debugUpdateDirectives [as updateDirectives] (core.js:11054) at checkAndUpdateView (core.js:10451)

Photo-list.component.html -

<div class="text-center mt-3 mb-3">
    <form>
        <input 
            class="rounded"
            type="search"
            placeholder="  search..."
            autofocus
            (keyup) = "filter = $event.target.value"
            >
    </form>
</div>

<ap-photos [photos] = "photos | filterByDescription: filter" ></ap-photos>

Photos.component.ts

import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
import { Photo } from '../../photo/photo';

@Component({
  selector: 'ap-photos',
  templateUrl: './photos.component.html',
  styleUrls: ['./photos.component.css']
})
export class PhotosComponent implements OnChanges {

  @Input() photos: Photo[]=[];
  rows: any[] = [];

  constructor() { }

  ngOnChanges(changes: SimpleChanges) {
    if(changes.photos){
      this.rows = this.groupColumns(this.photos);
    }
  }

  groupColumns(photos: Photo[]){
    const newRows = [];

    for( let index = 0; index < photos.length; index += 3){
      newRows.push(photos.slice(index, index + 3));
    }
    return newRows;
  }
}
1 resposta

Está chegando null no parâmetro "photos" do método "groupColumns". Você pode usar o operador "?." dentro do for, para acessar o parâmetro "length" de forma segura, igual no código abaixo:

  groupColumns(photos: Photo[]){
    const newRows = [];

    for( let index = 0; index < photos?.length; index += 3){
      newRows.push(photos.slice(index, index + 3));
    }
    return newRows;
  }

Sobre a razão do photos estar vindo null, aí vai ser necessário debuggar os passos anteriores.