gpt4 book ai didi

angular - 我怎样才能只显示 card.column 值与 angular2 中的 column.id 匹配的结果?

转载 作者:太空狗 更新时间:2023-10-29 17:26:51 27 4
gpt4 key购买 nike

我有下面的代码,它工作正常,它所做的是 ngFor 重复为列对象中的每一列创建一个列。

目前它在每一列中显示卡片对象中的每张卡片。

我想要它做的是仅在 WHERE column.id = card.column 列中显示卡片

如何修改我的代码来执行此操作?

  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();

}
}

最佳答案

正如@Langley 在他的评论中所说,我会为此创建一个自定义管道:

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]);
}
}

然后像那样使用它:

<div class="columns" *ngFor="#c of columns">
{{c.title}}
<div class="card" *ngFor="#card of cards | filter:c">{{card.title}}</div>
</div>

如果要兼顾更新,需要将pure属性设置为false:

@Pipe({
name: 'filter',
pure: false
})
@Injectable()
export class CardFilterPipe implements PipeTransform {
(...)
}

希望对你有帮助,蒂埃里

关于angular - 我怎样才能只显示 card.column 值与 angular2 中的 column.id 匹配的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34736315/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com