I am trying to create a pipe that will sort an array of a custom type.
// custom-object.ts
export class CustomObject {
constructor(
public someString: string,
public someNumber: number
) {}
}
In my html is:
// custom-object-form.component.ts
<div class="form-group">
<label for="cricos_course_code">Object: </label>
<select class="form-control" required [(ngModel)]="model.someString">
<option *ngFor="#object of (customObjects | sortArrayOfCustomObjects)" [value]="object.someString">{{object.someString}}</option>
</select>
</div>
Then the code for the pipe:
// sort-custom-object.pipe.ts
import {Pipe, PipeTransform} from 'angular2/core';
import {CustomObject} from '../custom-object';
@Pipe({name: 'sortArrayOfCustomObjects'})
export class SortArrayOfCustomObjectsPipe implements PipeTransform {
transform(arr:Array<CustomObject>): any {
return arr.sort((a, b) => {
if (a.someString > b.someString) {
return 1;
}
if (a.someString < b.someString) {
return -1;
}
// a must be equal to b
return 0;
});
}
}
Now I am getting an error in the console:
EXCEPTION: TypeError: Cannot read property 'sort' of undefined in [(customObjects | sortArrayOfCustomObjects) in FormComponent@7:24]
args: Array<string | number>?Array<CustomObject.someString | CustomObject.someNumber>is that those are properties not types. The type ofCustomObject.someStringis astring. Therefor you cannot useCustomObject.someStringas a type. Can you provide more information about your needs?p1: string, p2: numberetc. In my form I want to have 2 select fields that show a list of p1 in alphabetical order and p2 in descending order. I thought I could use a pipe like*ngFor="item of items | sortItems".