Pascal
Pascal

Reputation: 12885

Cannot read property '0' of undefined with custom filter pipe

Since I have created and added a custom filter pipe for an array I get this exception when the view loads:

TesttypesListComponent - inline template:35:14 caused by: Cannot read property '0' of undefined

This must have something todo I guess with how I load the data.

Before I added the pipe data loading worked!

I can put a breakpoint into the pipe but it never gets hit inside due to the error.

Anyone has an idea what I do wrong with my first pipe?

PIPE

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'TestTypePipe'
})
export class TestTypePipe implements PipeTransform {
    transform(testTypes, args?) {
        let [currentSubject, currentSchoolclass] = args;
        if (!currentSubject || !currentSchoolclass) {
            return [];
        }
        else {
            return testTypes.filter(s => {
                return s.subjectId == currentSubject.subjectId && s.schoolclassId == currentSchoolclass.schoolclassId;
            });
        }
    }
}

HTML

  <tbody>
          <tr *ngFor="let t of testTypes | TestTypePipe:currentSubject:currentSchoolclass; let i = index">
            <template [ngTemplateOutlet]="getTemplate(t)" [ngOutletContext]="{ $implicit: t, index: i }"></template>
          </tr>
        </tbody>

COMPONENT

  currentSubject: Subject;
  currentSchoolclass: Schoolclass;

      ngOnInit() {
this.route.params.subscribe(params => { this.schoolyearId = parseInt(params['id']); });

        this.testService.getTestTypes(this.schoolyearId).subscribe(data => {
          this.schoolclasses = data.schoolclasses.map(m => new Schoolclass(m));
          this.subjects = data.subjects.map(m => new Subject(m));

          for (let t of data.testTypes) {
            t.viewMode = ViewMode.Displaying;
            let testType = new AssignedTestType(t);
            this.testTypes.push(testType)
          }
        }

); }

Upvotes: 1

Views: 973

Answers (1)

Andr&#233; Werlang
Andr&#233; Werlang

Reputation: 5964

Pipe#transform takes optional top-level arguments, not a single args: [].

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'TestTypePipe'
})
export class TestTypePipe implements PipeTransform {
    transform(testTypes, ...args) {
        let [currentSubject, currentSchoolclass] = args;
        if (!currentSubject || !currentSchoolclass) {
            return [];
        }
        else {
            return testTypes.filter(s => {
                return s.subjectId == currentSubject.subjectId && s.schoolclassId == currentSchoolclass.schoolclassId;
            });
        }
    }
}

Upvotes: 2

Related Questions