在Angular中,可以使用Array
的sort()
方法来对对象列表按照指定的属性进行排序。以下是一个示例代码:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
- {{ item.name }}
`
})
export class AppComponent {
items = [
{ name: 'John', age: 25 },
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 20 }
];
}
在模板中使用*ngFor
指令来遍历对象列表,并显示每个对象的名称。
在组件中添加一个排序方法,用来按属性对对象列表进行排序:
sortItems(property: string) {
this.items.sort((a, b) => {
if (a[property] < b[property]) {
return -1;
} else if (a[property] > b[property]) {
return 1;
} else {
return 0;
}
});
}
这样,当点击按钮时,对象列表将会按照指定的属性进行排序。