[英]Angular sort by json property with Angular Material md-select
不確定如何使用md-select排序返回的json數據列表。 我需要管道嗎? 還是我組件中的一個函數?
[ { name: 'repo-name', created_at: '2017-1-15T10:30:37Z', updated_at: '2017-1-16T11:30:30Z'}, {...} ]
<!-- select with function if needed -->
<md-select placeholder="Sort by">
<md-option *ngFor="let sort of sorts" [value]="sort.value"
(click)="sortRepos( sort.value )">
{{ sort.viewValue }}
</md-option>
</md-select>
<!-- repeater -->
<md-list-item *ngFor="let repo of repos ">...</md-list-item>
export class ReposComponent implements OnInit, OnChanges {
repos: any[] = []; // populated via API call
errorMessage: string;
sorts: any[] = []; // for select options in constructor
sortBy = 'created_at'; // set default sortBy
constructor(private _repoService: ReposService ) {
this.sorts = [
{ viewValue: 'newest', value: 'created_at' },
{ viewValue: 'updated', value: 'updated_at' },
{ viewValue: 'alphabetical', value: 'name' },
];
}
sortRepos( value ) {
// ??? fails, doesn't seem like the right approach
this.sortBy = value;
this.sortBy === 'name' ? this.repos.sort( repo => repo.name )
: this.sortBy === 'created_at' ? this.repos.sort( repo => repo.created_at )
: this.repos.sort( repo => repo.updated_at );
}
ngOnInit() {
this._repoService.getRepos()
.subscribe( repos => { this.repos = repos;
console.log(repos); },error => this.errorMessage = <any>error );
}
ngOnChanges() {}
}
我在正確的軌道上嗎? 還是我需要一個以某種方式進入.name,.created_at和.updated_at並根據其進行排序的管道?
謝謝!
您可以創建自定義管道,也可以只在組件中編寫邏輯。 使用JavaScript中的Array#sort
函數。 這里的Angular沒什么特別的,只是您的自定義數據轉換。
排序功能接受應返回的比較功能。 1
, 0
或-1
基於所述比較的結果。 此函數的兩個參數是要比較的數組的兩項。
您當前傳遞的參數適用於sortBy
函數 ,因此您可能有興趣使用該參數而不是原始解決方案。
Array#sort
const sortedArr = arr.sort((a, b) => a.name > b.name ? 1 : -1)
_.sortBy
const sortedArr = _.sortBy(arr, x => x.name)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.