首页 > 解决方案 > 使用管道后如何修改我的数据流?

问题描述

我在ngFor directive哪里显示我的数据。我也在使用过滤器管道,所以当我在输入中输入内容时 - 我正在过滤这些项目。

HTML

<form [formGroup]='stateForm' class="mt-5">
    <input formControlName="search" />
</form>
<pre>{{ states | json }}</pre>
<div (click)='selectValue(s)' class='search-results'
    *ngFor="let s of states | searchFilter: getSearchValue() : propertyValueToShow; index as i"
    [ngClass]="{'highlight': i == selectedRow }" id="search-{{i}}">
    <a [innerHTML]="s[propertyValueToShow] | letterBold: getSearchValue()">
        {{s.name}}
    </a>
</div>

TS 文件 - 组件

export class AutocompleteComponent implements OnInit {

  stateForm: FormGroup;
  propertyValueToShow: string = 'name';
  states = [{ name: 'Texas', age: '33' }, { name: 'Michigan', age: '32' }, { name: 'Washington', age: '20' }]

  constructor(private fb: FormBuilder) {
    this.initForm()
  }

  initForm(): FormGroup {
    return this.stateForm = this.fb.group({
      search: []
    })
  }

getSearchValue() {
return this.stateForm.value.search;
}

}

*我的过滤管

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'searchFilter'})
export class SearchFilterPipe implements PipeTransform {
    transform(value: any, search: string, prop = null): any {
         if  (!search) {return value; }
         let solution = value.filter(v => {
            if ( !v ) { return; }
            return prop
                         ?
                         v[prop].toLowerCase().indexOf(search.toLowerCase()) !== -1
                         :
                         v.toLowerCase().indexOf(search.toLowerCase()) !== -1;
        });
         return solution;
    }
};

所以当我在输入中输入内容时,ngFor项目被过滤,但在`pre标签中我仍然可以看到具有初始值的状态。

我怎样才能在我的管道之后使实际数据也被修改?

我试过了

 getSearchValue() {
    let solution = this.states.filter(v => {
      return this.propertyValueToShow
                   ?
                   v[this.propertyValueToShow].toLowerCase().indexOf(this.stateForm.value.search.toLowerCase()) !== -1
                   :
                   v[this.propertyValueToShow].toLowerCase().indexOf(this.propertyValueToShow.toLowerCase()) !== -1;
    });
    this.states = Object.assign([], solution);
    this.states = solution;
    return this.stateForm.value.search;
  }

但后来我得到错误

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '[
  {
    "name": "Texas",
    "age": "33"
  },
  {
    "name": "Michigan",
    "age": "32"
  },
  {
    "name": "Washington",
    "age": "20"
  }
]'. Current value: '[
  {
    "name": "Texas",
    "age": "33"
  },
  {
    "name": "Washington",
    "age": "20"
  }
]'.

我该如何解决这个问题?

标签: angularrxjsangular-directive

解决方案


推荐阅读