Angular 具有角度材质md select的角度按json属性排序
不确定如何使用md select对返回的json数据列表进行排序。我需要烟斗吗?或者只是我的组件中的一个函数 返回的json对象 repos.component.html repos.component.ts 我走对了吗?或者我需要一个管道以某种方式进入.name、.created\u at和.updated\u at并根据它进行排序Angular 具有角度材质md select的角度按json属性排序,angular,sorting,select,drop-down-menu,angular-material2,Angular,Sorting,Select,Drop Down Menu,Angular Material2,不确定如何使用md select对返回的json数据列表进行排序。我需要烟斗吗?或者只是我的组件中的一个函数 返回的json对象 repos.component.html repos.component.ts 我走对了吗?或者我需要一个管道以某种方式进入.name、.created\u at和.updated\u at并根据它进行排序 谢谢 您可以创建自定义管道,也可以只在组件中写入逻辑。使用JavaScript中的函数。这里的Angular没有什么特别之处,它只是您自定义的数据转换 排序函数接
谢谢 您可以创建自定义管道,也可以只在组件中写入逻辑。使用JavaScript中的函数。这里的Angular没有什么特别之处,它只是您自定义的数据转换 排序函数接受一个应该返回的比较函数。1、0或-1(基于比较结果)。此函数的两个参数是要比较的数组的两项 您当前传递的参数是适合的,因此您可能会对使用该参数而不是普通的解决方案感兴趣 阿莱索特 _sortBy先生
您可以创建自定义管道,也可以只在组件中编写逻辑。使用JavaScript中的函数。这里的Angular没有什么特别之处,它只是您自定义的数据转换 排序函数接受一个应该返回的比较函数。1、0或-1(基于比较结果)。此函数的两个参数是要比较的数组的两项 您当前传递的参数是适合的,因此您可能会对使用该参数而不是普通的解决方案感兴趣 阿莱索特 _sortBy先生
你的思路是对的,但我会按照@Lazar的建议考虑使用Lodash。我想你不需要一根管子。我注意到的是,在代码中的任何地方都没有将排序后的数组赋回repos数组。对this.repos.sort的调用将返回一个新数组-它不会更改现有数组。你应该这样做。repos=这个。repos。排序。。。为了让分类生效。你的思路是对的,但我会按照@Lazar的建议考虑使用Lodash。我想你不需要一根管子。我注意到的是,在代码中的任何地方都没有将排序后的数组赋回repos数组。对this.repos.sort的调用将返回一个新数组-它不会更改现有数组。你应该这样做。repos=这个。repos。排序。。。为了使这类协议生效。
[ { 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() {}
}
const sortedArr = arr.sort((a, b) => a.name > b.name ? 1 : -1)
const sortedArr = _.sortBy(arr, x => x.name)