如何观察“ searchTerm”输入字段的值变化?

时间:2018-10-21 15:23:25

标签: angular ngrx

我有两个可以正常工作的观察值:

@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;

ngOnInit() {
  ...
  merge(this.sort.sortChange, this.paginator.page)
  .pipe(
    startWith({}),
    switchMap(() => {
      return this.getUsers(this.sort.active, this.sort.direction, this.paginator.pageIndex);
    }),
    map(userApi => {

这允许在更新排序或分页时调用getUsers服务方法。

现在,我还希望在键入搜索词时调用此服务方法:

@ViewChild(String) searchTerm: string;
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;

ngOnInit() {
  ...
  merge(this.searchTerm.length, this.sort.sortChange, this.paginator.page)
  .pipe(
    startWith({}),
    switchMap(() => {
      return this.getUsers(this.searchTerm, this.sort.active, this.sort.direction, this.paginator.pageIndex);
    }),
    map(userApi => {

具有以下模板标记:

<mat-form-field>
    <input matInput #searchTerm (keyup)="search($event.target.value)" placeholder="User name" autocomplete="off">
</mat-form-field>

但是,即使在页面加载时也不会调用service方法。

我的想法是让searchTerm为可观察的,并通过merge方法观察该可观察的事物。这样,我只有一个方法调用getUsers服务方法。

我也尝试了此语句(不使用.length),但没有任何改变:

merge(this.searchTerm, this.sort.sortChange, this.paginator.page)

更新:我现在正在尝试以下方法:

@ViewChild('searchTerm') searchTerm: ElementRef;

merge(this.searchTerm.nativeElement.changes, this.sort.sortChange, this.paginator.page)

search事件处理程序确实更新了searchTerm成员变量:

  search(searchTerm: string) {
    this.searchTerm.nativeElement.value = searchTerm.trim().toLowerCase();

    if (this.paginator) {
      this.paginator.firstPage();
    }
  }

我想我可以获取输入字段元素的值来调用服务方法:

return this.getUsers(this.searchTerm.nativeElement.value, this.sort.active, this.sort.direction, this.paginator.pageIndex);

但是merge如果包含this.searchTerm.nativeElement.changes,则不会触发:

merge(this.searchTerm.nativeElement.changes, this.sort.sortChange, this.paginator.page)

如何观察searchTerm输入字段的值变化?

1 个答案:

答案 0 :(得分:0)

我终于可以使用EventEmitter对象解决问题了:

@Input() searchTerm: string;
@Output() searchTermEvent = new EventEmitter<{ value: string }>();

merge(this.searchTermEvent, this.sort.sortChange, this.paginator.page)
  .pipe(
    startWith({}),
    switchMap(() => {
      this.isLoadingResults = true;
      return this.getUsers(this.searchTerm, this.sort.active, this.sort.direction, this.paginator.pageIndex);
    }),

该事件与处理程序一起发出:

search(searchTerm: string) {
  this.searchTerm = searchTerm;
  this.searchTermEvent.emit({
    value: this.searchTerm
  });

  if (this.paginator) {
    this.paginator.firstPage();
  }
}

在每个输入字符上启动getUsers服务方法。

也许有更好的选择,但是目前还可以。