我正在努力订阅Angular 4中的选择下拉列表更改。
我的searchType
变量的更改仅在通过点击事件调用test()
函数后才可见,但是我需要Angular立即订阅更改。
旁注:
App.component.html
<select name="searchType" id="searchType" #searchType>
<option value="movie_title"> movie title</option>
<option value="director">director</option>
<option value="actor"> actor</option>
</select>
App.component.ts
@ViewChild('searchType') select: ElementRef;
searchType: number;
constructor(private service: ServiceService) {}
ngOnInit() {
this.searchType = this.select.nativeElement.options.selectedIndex;
this.service.sendSearchType(this.searchType);
}
test() {
this.searchType = this.select.nativeElement.options.selectedIndex;
this.service.sendSearchType(this.searchType);
}
service.service.ts
searchType = new Subject<number>();
sendSearchType(id: number) {
this.searchType.next(id);
}
getSearchType(): Observable<number> {
return this.searchType.asObservable();
}
最后 filter.pipe.ts 订阅更改
searchType: number;
private subscription: Subscription;
constructor(private service: ServiceService) {
this.service.getSearchType().subscribe(
(id) => (this.searchType = id)
);
}
transform(value: any[], filter: string): any[] {
filter = filter ? filter.toLocaleLowerCase() : null;
return filter ? value.filter(
(product) =>
this.auxiliaryFunction(product, filter)
) : value;
}
auxiliaryFunction(product, filter) {
if (this.searchType === 2) {
return (product.actor.toLocaleLowerCase().indexOf(filter) !== -1)
} else if (this.searchType === 1) {
return (product.director.toLocaleLowerCase().indexOf(filter) !== -1)
} else {
return (product.movie.toLocaleLowerCase().indexOf(filter) !== -1)
}
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
我哪里出错了? 将不胜感激任何解决方案。
答案 0 :(得分:0)
您必须注意select元素的更改。我做了这个live example,我希望它有所帮助。 (的 app.component.ts 强>)
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import { AfterViewInit } from '@angular/core';
...
ngAfterViewInit() {
const $selector = Observable.fromEvent(this.select.nativeElement, 'change');
$selector.subscribe(() => {
this.searchType = this.select.nativeElement.options.selectedIndex;
this.service.sendSearchType(this.searchType);
});
}
(的 filter.pipe.ts 强>)
constructor(private service: AppService) {
this.service.getSearchType().subscribe(
(id) => {
console.log(`${id}px`);
return (this.searchType = id);
}
);
}
答案 1 :(得分:0)
你也可以使用事件绑定(live exmaple),但我真的更喜欢被动反应。 ( app.component.html )
<select name="searchType" id="searchType" (change)="onSelect()" #searchType>
<option value="movie_title">movie title</option>
<option value="director">director</option>
<option value="actor"> actor</option>
</select>
(的 app.component.ts 强>)
onSelect() {
this.searchType = this.select.nativeElement.options.selectedIndex;
this.service.sendSearchType(this.searchType);
}