I have the below code and it works fine, what it does is ngFor repeat to create a column for each column in the column object.
Currently it shows every card from the cards object in every column.
What i want it to do is show only cards in the column WHERE column.id = card.column
How can I modify my code to do this?
import {Input, Output, EventEmitter, Component, Injectable} from 'angular2/core'
import {NgFor} from 'angular2/common'
import {Observable} from 'rxjs/Observable';
interface Card {
id?: number;
title?: string;
column?: number;
}
@Injectable()
export class DataService {
cards$: Observable<Array<Card>>;
private _cardsObserver: any;
private _dataStore: Array<Card>;
constructor(){
this._dataStore = [
{id: 1, title: 'Card A', column: 1},
{id: 2, title: 'Card B', column: 2},
{id: 3, title: 'Card C', column: 2}
];
this.cards$ = new Observable(observer =>
this._cardsObserver = observer).share();
}
loadCards() {
this._cardsObserver.next(this._dataStore);
}
addCard(){
this._dataStore.push({id: 4, title: 'Card D', column: 3});
this._cardsObserver.next(this._dataStore);
}
getColumns(){
var columns = [
{id: 1, title: 'Column One'},
{id: 2, title: 'Column Two'},
{id: 3, title: 'Column Three'}
];
return columns;
}
}
@Component({
selector: 'app',
providers: [DataService],
directives: [],
template: `
<button (click)="dataService.addCard()">Add Card</button>
<div class="columns" *ngFor="#c of columns">
{{c.title}}
<div class="card" *ngFor="#card of cards">{{card.title}}</div>
</div>
`
})
export class App {
private cards: Array<Card>;
private columns: any;
constructor(public dataService: DataService) {
dataService.cards$.subscribe(updatedCards => this.cards = updatedCards);
dataService.loadCards();
this.columns = dataService.getColumns();
}
}
Like @Langley said in his comment, I would create a custom pipe for this:
import {Injectable, Pipe} from 'angular2/core';
@Pipe({
name: 'filter'
})
@Injectable()
export class CardFilterPipe implements PipeTransform {
transform(items: any[], args: any[]): any {
return items.filter(item => item.column === args[0]);
}
}
And use it like that:
<div class="columns" *ngFor="#c of columns">
{{c.title}}
<div class="card" *ngFor="#card of cards | filter:c">{{card.title}}</div>
</div>
If you want to take into account update, you need to set the pure attribute to false:
@Pipe({
name: 'filter',
pure: false
})
@Injectable()
export class CardFilterPipe implements PipeTransform {
(...)
}
Hope it helps you, Thierry
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With