我对 Angular 很陌生,我正在从互联网上的一些教程中学习它。现在我想学习如何使用 orderby 对我的英雄表的表头进行排序。我不明白管道以及如何从组件中调用它。我只是不明白如何使用管道。我不明白他们何时在教程中解释了这一点。有人可以向我解释一下,以便我了解真正发生的事情吗?我不明白转换方法。这是我的代码,你能看出有什么问题吗?提前致谢
Superheroes.component.html
enter code here`
<tr *ngFor="let hero of heroes | orderBy:['-hero.id', 'hero.name',
'-hero.phone-number', 'hero.country']">
I generated the pipe, but it is not working.
Orderby.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'orderby', pure: false })
export class OrderbyPipe implements PipeTransform {
transform(heroes: any[], name: string): any[] {
heroes.sort((a: any, b: any) => {
if (a[name] < b[name]) {
return -1;
} else if (a[name] > b[name]) {
return 1;
} else {
return 0;
}
});
return heroes;
}
}
Superheros.component.ts
import { Component, OnInit, Pipe, PipeTransform, Input } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { OrderbyPipe } from '../orderby.pipe';
import { Heroes } from '../model/hero';
import { HeroService } from '../services/hero.service';
@Component({
selector: 'app-superheroes',
templateUrl: './superheroes.component.html',
styleUrls: ['./superheroes.component.css'],
providers: [HeroService],
})
export class SuperheroesComponent implements OnInit {
isValidFormSubmitted: boolean = null;
searchForm = null;
statusmessage: string = "Nothing submitted";
//records: Array<any>;
isDesc: boolean = false;
column: string = 'Name';
direction: number;
heroes: Hero[];
constructor(private heroService: HeroService) { }
ngOnInit(): void {
this.searchForm = new FormGroup({
searchmode: new FormControl('', Validators.required)
});
// this.setDefaultValues();
this.getHeroes();
}
getHeroes(): void {
this.heroService.getHeroes().then(heroes => this.heroes = heroes);
}
sort(property) {
this.isDesc = !this.isDesc;
this.column = name;
this.direction = this.isDesc ? 1 : -1;
}
}