使用Angular中的过滤器更新列表

时间:2019-05-14 12:59:49

标签: jquery angular

我想使用angular的过滤器选项更新列表数据。

 import { Component, OnInit } from '@angular/core';
    @Component({
      selector: 'app-category',
      templateUrl: './category.component.html'
    })
    export class CategoryComponent implements OnInit {

      records: Array<any>;
      isDesc: boolean = false;
      column: string = 'CategoryName';
      constructor() { }

      ngOnInit() {
        this.records= [
          { CategoryID: 1,  CategoryName: "Beverages", Description: "Coffees, teas" },
          { CategoryID: 2,  CategoryName: "Condiments", Description: "Sweet and savory sauces" },
          { CategoryID: 3,  CategoryName: "Confections", Description: "Desserts and candies" },
          { CategoryID: 4,  CategoryName: "Cheeses",  Description: "Smetana, Quark and Cheddar Cheese" },
          { CategoryID: 5,  CategoryName: "Grains/Cereals", Description: "Breads, crackers, pasta, and cereal" },
          { CategoryID: 6,  CategoryName: "Beverages", Description: "Beers, and ales" },
          { CategoryID: 7,  CategoryName: "Condiments", Description: "Selishes, spreads, and seasonings" },
          { CategoryID: 8,  CategoryName: "Confections", Description: "Sweet breads" },
          { CategoryID: 9,  CategoryName: "Cheeses",  Description: "Cheese Burger" },
          { CategoryID: 10, CategoryName: "Grains/Cereals", Description: "Breads, crackers, pasta, and cereal" }
         ];
         // here i want to update my list
          this.records.filter(u=>if(u.CategoryName=='Confections'){u.Description = 'Some description'}); // here the filter is throwing compile time exception
      }
    }

我正在尝试使用角度过滤器选项更新列表内容,但出现编译时异常,请帮助解决该问题。

1 个答案:

答案 0 :(得分:1)

我认为您不需要使用Array.filterFrom the docs

  

filter()方法创建一个新数组,该数组包含所有通过提供的功能实现的测试的元素。

您似乎只是在尝试更新与谓词匹配的项的属性。

相反,您可以只使用一个简单的循环:

for (let u of this.records) {
  if(u.CategoryName == 'Confections') {
    u.Description = 'Some description'
  }
}

出现编译错误的原因是,Array.filter()期望布尔返回函数适用于数组中的每个项目,例如

this.records.filter(x => x.prop === 'abc')

this.records.filter(x => {
  return x.prop === 'abc';
});