0
votes

I am using custom pipe with ternary operator for *ngFor, getting errors. Not knowing how to resolve. Please kindly help.

html:

<div *ngFor="let x of y | limitTo: y.limit ? y.length : 10">

truncate.pipe.ts:

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

@Pipe({
  name: 'limitTo'
})
export class TruncatePipe {
  transform(value: string, limit:number) : string {
    let trail = '...';

    return value.length > limit ? limit + trail : value;
  }
}

app.module.ts:

import { NgModule }      from '@angular/core';
import {  TruncatePipe }   from './truncate.pipe';

@NgModule({
  imports:      [
  ],
  declarations: [
    TruncatePipe
  ],
  exports: [ 
  ]
})

export class AppModule { }

Error:

Cannot find a differ supporting object '10...' of type 'string'. NgFor only supports binding to Iterables such as Arrays`. in html file

3
@Dixit Savaliya pipe is not working for *ngFor.3103
add parenthesis, Angular think that the last ":" are a new parameter of the pipe "let x of y | limitTo: (y.limit ? y.length : 10)"Eliseo
*ngFor doesn't work with strings. You should use array in *ngFor e. g. angular.io/guide/…Robert Daraż
please provide a minimal reproducible example, best would be a stackblitz, what is y?AJT82

3 Answers

1
votes

You're passing string to the ngFor which is not accepted. make sure you pass the array. i.e "x" should be array

0
votes

You are passing whole array to your pipe. If length is higher lower than the limit it will return array unchanged. Otherwise it will return array length followed by trail.

You most likely have an array y = ['str-1', 'str-2', 'str-3'...] Your pipe call is limitTo: y.limit ? y.length : 10 If itterable y doesn't have limit field or if it's 0 it will default to 10.

In your question pipe was called with arguments value = y and limit = 10 Trail is '...';

If length of array y is lower than limit (in this example 10, which is false) it would end up returning the array unchanged.

Otherwise it will return limit + trail which equals 10 + '...'. This is a string.

Strings are not iterable and therefore you will receive an error.

0
votes

Thank you all

Solution Worked:

<div *ngFor="let x of (y.limit ? (y | slice: 0 : y.length) : (y | slice: 0 : 10))">