当前正在尝试使用自定义管道过滤我的* ngFor列表项,以切换评论状态为已打开或已关闭的帖子。似乎在设置它时遇到障碍。
代码如下:
app.component.html
<select (change)="onChange($event.target.value)">
<option value="all" selected="selected">All</option>
<option value="open">Open</option>
<option value="closed">Closed</option>
</select>
<ul>
<li *ngFor="let post of posts | myPipe:commentStatus">
<h1>{{ post.title.rendered }}</h1>
comment status: {{ post.comment_status }}
</li>
</ul>
app.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'rest-ang';
posts = [];
wpUrl = 'http://wprest.local/wp-json/wp/v2/posts';
filterByComments= '';
//postsTitle: any = {};
constructor(private http: HttpClient) {}
ngOnInit(){
return this.http.get(this.wpUrl)
.subscribe(data => {
for(let key in data){
if(data.hasOwnProperty(key)){
this.posts.push(data[key]);
}
}
console.log(data);
//console.log(this.postsTitle);
})
}
onChange(optionFromMenu:string) {
if(optionFromMenu === 'all'){
this.posts = this.posts;
}
if(optionFromMenu === 'closed') {
this.posts = this.posts.filter(data => {
return this.posts.includes('closed');
});
}
}
}
mypipe.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'mypipe'
})
export class MyPipe implements PipeTransform {
transform(posts: any[], comment_status: any): any {
return posts;
console.log(comment_status);
if(comment_status === 'all') {
}
}
}
尽管目前我所有的更改都是通过component.ts进行的,但我想在pipe.ts文件中进行设置,但是简单地使工作变得有些困难。任何建议表示赞赏。
如果有帮助,可以通过Angular CLI使用Angular 6设置应用。
答案 0 :(得分:0)
您可以使用模板驱动的表单方式,在选择字段上使用[(ngModel)]
,并且不再需要(change)
方法逻辑。因此,将视图代码更新为:
<select [(ngModel)]="commentStatus">
<option value="all" selected="selected">All</option>
<option value="open">Open</option>
<option value="closed">Closed</option>
</select>
<ul>
<li *ngFor="let post of posts | myPipe:commentStatus">
<h1>{{ post.title }}</h1>
comment status: {{ post.comment_status }}
</li>
</ul>
然后从管道类更新您的transform
方法,以便它将采用commentStatus
变量的当前值,然后过滤posts
数组。因此,管道代码可能类似于:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'myPipe'
})
export class MyPipePipe implements PipeTransform {
transform(posts: any[], commentStatus: any): any {
if(!commentStatus) {
return posts;
}
if(commentStatus === 'all') {
return posts;
} else if(commentStatus === 'open' || commentStatus === 'closed') {
let filterdPosts = posts.filter((i) => {
return i.comment_status == commentStatus;
});
return filterdPosts;
}
}
}