【发布时间】:2018-09-11 16:57:09
【问题描述】:
当前尝试使用自定义管道过滤我的 *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 设置的。
【问题讨论】:
标签: wordpress angular typescript wordpress-rest-api