menu

Questions & Answers

How to return an array to its first value? Angular

I need your help. In my Angular application, I accept an array and try to filter it by a certain field. The point is that I have the normal filtering working, however, I need to return the array to the very first value: as if the page had just loaded. I tried to do this with the spread operator, but when I click on it, I have no element on the page. Please tell me how to implement this? Thank you very much

HTML

<div>
    <select
      formControlName="category"
      (change)="filterProductsCategorySelectOption()">
      <option [value]="firstDataValue">Reset</option>
      <option
        *ngFor="let category of allProductsCategories"
        [value]="category"
      > {{category}} </option>
    </select>
  </div>

  <div *ngFor="let product of filteredProductList" class="different"></div>

TypeScript

public allProductsCategories: string[] = ["electronics", "jewelery", "men's clothing", "women's clothing"]
public allProductList: any;
public filteredProductList: any;
public firstDataValue: any;

ngOnInit(): void {
   this.form = new FormGroup({
     category: new FormControl(null),
   })

   this.productService.getAllProducts().subscribe(value => {
     this.allProductList = this.filteredProductList = value;
   })
   this.firstDataValue = [...filteredProductList];
}

public filterProductsCategorySelectOption(): void {
   const categoryOptionValue = this.form.controls['category'].value;
   this.filteredProductList = this.allProductList.filter(el => el.category === categoryOptionValue);
}
Comments:
2023-01-20 11:42:02
use setValue / patchValue on the form
Answers(0) :