Я добавил trackBy для обновления моего шаблона. Это работа. Но когда я добавил ngx-pipe 'reverse' *ngFor="let comment of comments | reverse; trackBy:trackByFn"
reverse игнорировался. Если я использую только «реверс», это нормально. Как это решить?
шаблон:
<form class="mb-2" #addCommentForm="ngForm" (ngSubmit)="addComment()">
<textarea class="form-control form-control-sm" type="text" placeholder="Type some comment!" name="content" [(ngModel)]="comment.content"></textarea>
<button type="submit" class="btn btn-success btn-sm offset-sm-10 col-sm-2">Add</button>
</form>
<div *ngFor="let comment of comments | reverse; trackBy:trackByFn" class="card mb-2">
<div class="card-body pb-1">
<p class="card-text mb-1">{{comment.content}}</p>
<a *ngIf="comment.userId === myId" (click)="deleteComment(comment.id)" class="card-link mb-1 text-danger">Delete</a>
</div>
</div>
компонент:
export class CommentComponent implements OnInit {
@Input() comments: Comment[];
@Input() users: User[];
comment: Comment;
myId: number;
constructor(private commentService: CommentService, private alertify: AlertifyService,
private router: Router, private authService: AuthService ) {
}
ngOnInit() {
this.comment = {
id: 0,
userId: 0,
ticketId: 0,
content: ''
};
this.myId = parseInt(this.authService.decodedToken.nameid, 10);
}
selectUser(id: number): User {
return this.users.find(user => user.id === id);
}
addComment() {
this.commentService.addComment(this.comment).subscribe((data: Comment) => {
this.alertify.success('Comment has been added');
this.comments.push(data);
}, error => {
this.alertify.error(error);
});
}
deleteComment(id: number) {
this.commentService.deleteComment(id).subscribe(() => {
this.comments.splice(this.comments.findIndex(c => c.id === id), 1);
this.alertify.success('Comment deleted successfuly');
}, error => {
this.alertify.error('Failed to delete commment');
});
}
trackByFn(index, item) {
return index; // or item.id
}
}