0

通过 WebService 我向前端发送一个 Json 并将其映射以将其所有内容放入一个表中,我想建立一个搜索方法来仅查看具有搜索到的字母的行。

组件.ts

allCountries:allCountries[];
applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.allCountries.filter = filterValue.trim().toLowerCase();
  }     ^^^^^^^^^^^^
           ERROR

映射

export class allCountries{
    name:string;
    iso2:string;
    iso3:string;
    unicode:string;
    dial:string;
    currency:string;
    capital:string;
    continent:string;
}

HTML

<mat-label for="ricerca">Ricerca</mat-label>
            <input matInput type="text" name="searchString" (keyup)="applyFilter($event)" placeholder="Type to search..." />

      <table mat-table [dataSource]="allCountries">

            <ng-container matColumnDef="name">
                    <th mat-header-cell *matHeaderCellDef>Nazione</th>
                    <td mat-cell *matCellDef="let allCountries">{{allCountries.name}}</td>
                </ng-container>

                <ng-container matColumnDef="iso2">
                    <th mat-header-cell *matHeaderCellDef>iso 2</th>
                    <td mat-cell *matCellDef="let allCountries">{{allCountries.iso2}}</td>
                </ng-container>

错误

error TS2322: Type 'string' is not assignable to type '{ <S extends allCountries>(callbackfn: (value: allCountries, index: number, array: allCountries[]) => value is S, thisArg?: any): S[]; (callbackfn: (value: allCountries, index: number, array: allCountries[]) => unknown, thisArg?: any): allCountries[]; }'.

我知道错误是因为“过滤器”可用于简单数组而不是对象数组。我没有发布所有代码,因为它与我的问题无关,因此毫无用处。谢谢您的帮助

4

1 回答 1

0

这里的问题是它Array.filter是一个函数而不是一个属性。所以不能这样分配:this.allCountries.filter = .

相反,应该将它作为一个函数调用,作为参数传递另一个将进行过滤的函数。

过滤名称中包含键入的子字符串的国家/地区的示例(函数String.includes()

  this.filteredCountries = this.allCountries.filter(
      obj => obj.name.toLowerCase().includes(filterValue.trim().toLowerCase())    
  );

保留两个单独的数组是个好主意,一个对所有国家/地区不可变(allCountries),另一个根据输入的文本(例如:)具有给定的过滤国家/地区filteredCountries。否则每个过滤周期都会减少数组,最终国家数组将为空。

这是一般的想法:

export class AppComponent {
  allCountries = [
    {
      name: "England"
    },
    {
      name: "France"
    }
  ];

  filteredCountries = [];
  ngOnInit() {
    this.filteredCountries = this.allCountries;
  }

  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    if (!filterValue) {
      //empty filter, show all countries:
      this.filteredCountries = this.allCountries;
    } else {
      console.log("Filtering for " + filterValue);
      this.filteredCountries = this.allCountries.filter(
        obj => obj.name.toLowerCase().includes(filterValue.trim().toLowerCase())
      );
    }
  }
}

并且在 html 而不是allCountries一个应该绑定到filteredCountries

<table mat-table [dataSource]="filteredCountries">

  <!-- code omitted for brevity -->

</table>

这是一个带有工作代码的stackblitz:

https://stackblitz.com/edit/angular-ivy-lzkxnr?file=src/app/app.component.ts

于 2020-10-21T10:02:57.060 回答