首页 > 解决方案 > 角表排序,没有角材料

问题描述

我想在我的表格中搜索,但我希望表格中填充我的数据。目前,只有在我开始在搜索栏中输入时才会填写。

我认为问题出在初始化组件时 productsArray 为空

我的数据来自项目中的 JSON 文件。

下面你可以看到我目前拥有的

export class TableComponent implements OnInit {
      searchText: any;
      productsArray: Products[] = [];
      filteredArray = [...this.productsArray];

      constructor(private http: HttpClient) {}

      ngOnInit(): void {
        this.getProducts().subscribe((res) => {
          this.productsArray = res;
        });
      }
      getProducts(): Observable < Products[] > {
        return this.http
          .get < any > ('assets/mock.data.json')
          .pipe(map((results) => results.data));
      }
      filterArray(): any {
        if (!this.productsArray.length) {
          this.filteredArray = [];
          return;
        }

        if (!this.searchText) {
          this.filteredArray = [...this.productsArray];
          return;
        }

        const products = [...this.productsArray];
        const properties = Object.keys(products[0]);

        this.filteredArray = products.filter((product) => {
          return properties.find((property) => {
              const valueString = product[property].toString().toLowerCase();
              return valueString.includes(this.searchText.toLowerCase());
            }) ?
            product :
            null;
        });
      }
    }
代码名称类别
<tbody *ngFor="let product of filteredArray; let i = index">
  <tr>
    <td>{{ product.code }}</td>
    <td>{{ product.name }}</td>
    <td>{{ product.category }}</td>
  </tr>
</tbody>

标签: angular

解决方案


初始化时filteredArray,它是空的。只有在被调用filteredArray时才会填充一些值。所以在 ngOnInit() 中filterArray()提供值。filteredArray尝试这个:

ngOnInit(): void {
    this.getProducts().subscribe((res) => {
      this.productsArray = res;
      this.filteredArray = [...this.productsArray];
    });
  }

推荐阅读