Holger Rattenscheid
Holger Rattenscheid

Reputation: 197

How to save model manipulation of *ngFor with pipes? - "#item of (result = (items | orderAsc))" doesn't work in A2

So I populate a table with *ngFor and use pipes to filter and order the given items array. This works perfectly and the table rows are created as expected. But I also wan't to use the result of the pipes in my component hosting the table. How can this be achieved with angular2?

my current html:

<tr *ngFor="#item of items | orderAsc">{{item.name}}</tr>

the old angularJS way of saving the result:

<tr *ngFor="#item of (result = (items | orderAsc))">{{item.name}}</tr>

where "result" could be used in the corresponding controller.

What is the angular2 way of achieving this? I'd like to keep the filtering in the html template and not move it into the component.

Upvotes: 3

Views: 2024

Answers (2)

VictorNS
VictorNS

Reputation: 19

According the official documentation it should be:

<tr *ngFor="let item of items | orderAsc as result">{{item.name}} ( {{result.length}} )</tr>

Upvotes: 0

Thierry Templier
Thierry Templier

Reputation: 202326

As far as I know, the old way isn't supported.

I have a workaround for this but I don't know if it's a clean way to do ;-)

You could implement a custom pipe (the dump one in the following sample) you put at the end of your pipe chain to save the filtered value into the component

@Pipe({
  name: 'filter'
})
export class FilterPipe {
  (...)
}

@Pipe({
  name: 'sort'
})
export class FilterPipe {
  (...)
}

@Pipe({
  name: 'dump'
})
export class DumpPipe {
  constructor(@Inject(forwardRef(() => AppComponent)) app:AppComponent) {
    this.app = app;
  }

  transform(array: Array<string>, args: string): Array<string> {
    this.app.save(array);
    return array;
  }
}

@Component({
  selector: 'my-app', 
  template: `
    <div>
      <span *ngFor="#l of (list | filter | sort)">{{l}}</span>
    </div>
  `,
  pipes: [ FilterPipe, SortPipe, DumpFilter ]
})
export class AppComponent {
  constructor() {
    this.list = [ 'n', 'g', 'a', 'u', 'r', 'l' ];
  }

  save(array) {
    console.log('save array = '+array);
  }
}

When the expression is evaluated, the dump pipe calls the save method of the component with the filtered and sorted value.

Here is the corresponding plunkr: https://plnkr.co/edit/xv4BTq7aCyKJSKcA9qB9?p=preview

Hope it helps you, Thierry

Upvotes: 2

Related Questions