2
DOM로드시 잘 작동하는 orderby 파이프를 구현했습니다. 그러나 목록에 새 항목을 추가하면 파이프가 활성화되지 않고 목록에 추가 된 새 항목이 순서가 아니라 목록의 마지막 위치에 추가됩니다.각도 2 목록에 새 항목을 추가 할 때 사용자 지정 파이프가 순서를 변경하지 않음
파이프 :
import { PipeTransform, Pipe } from '@angular/core';
import { ITeam } from './team';
@Pipe({
name: "LeagueFilter"
})
export class LeagueFilterPipe implements PipeTransform {
transform(value: any[], filterBy: string): any[] {
filterBy = filterBy ? filterBy.toLocaleLowerCase() : null
for (let i = 0; i < value.length - 1; i++) {
for (let j = 0; j < value.length - 1; j++) {
if (value[j][filterBy] < value[j + 1][filterBy]) {
let temp = value[j]
value[j] = value[j + 1]
value[j + 1] = temp
}
}
}
return value;
}
}
되는 HTML :
<div class="container">
<div class="row">
<div class="col-sm-offset-1 col-sm-4">
<h2>
{{leagueTable}}
</h2>
<table class="table table-responsive">
<thead>
<tr>
<th>#</th>
<th>Team</th>
<th>Points</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let team of teams | LeagueFilter:'points'; let i = index">
<td>{{i+1}}</td>
<td>{{team.name}}</td>
<td>{{team.points}}</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="row">
<fieldset class="col-sm-offset-1 col-lg-3">
<legend>Add Team</legend>
<label for="name">Name </label>
<input type="text" name="" value="" [(ngModel)] = "newTeam.name" />
<br/>
<label for="name">Points</label>
<input type="text" name="" value="" [(ngModel)] = "newTeam.points" />
<button type="submit" (click)="addTeam()">Add</button>
</fieldset>
</div>
</div>
성분 :
import { Component } from '@angular/core';
import { ITeam } from './team';
@Component({
selector: 'league-list',
moduleId:module.id,
templateUrl: 'league-list.component.html',
styleUrls: ['league-list.component.css']
})
export class LeagueListComponent {
leagueTable: string = "La Liga"
teams: ITeam[] = [
{ name: "Barcelona", points: 84 },
{ name: "Real Madrid", points: 85 },
{ name: "Valencia", points: 78 },
{ name: "Sevilla", points: 80 },
{ name: "Villareal", points: 62 },
]
newTeam:ITeam = { name:"", points:null };
addTeam():void{
this.teams.push(this.newTeam)
}
}