0

I have an angular application displaying a list of names. I have a search input to filter that list.

<input [ngModel]="searchStr" (ngModelChange)="modelChange($event)" type="text" id="employeeName">

The component has this logic for modelChange(), to capture the input string and filter my names by that string. This data initially comes from a service called in ngInit(). My issue is I am overwriting my names array with a filtered down array each time a key stroke is made in the input box. How can I write this logic to reset the array back to it's original contents when the input is blank?

modelChange(str: string): void {
  debugger;
  this.searchStr = str;

  this.employeeList = this.employeeList.filter(emp => emp.name.includes(this.searchStr));
}

HTML template

<div *ngFor="let employee Of employeeList>
    employee.name
</div>

2 Answers 2

1

You are overwriting the same array in modelChange, so if you want to revert to the original array (on some condition) you must keep a reference of your original array somewhere, or dont overwrite the original array at all. Maintain another array for display purpose, lets say you name it displayArr

Your code would update like this

public displayArr:any[] = []
modelChange(str: string): void {
  debugger;
  this.searchStr = str;

  //if some search string is provided, then filter the original array
  if(str)
  {
    this.displayArr = this.employeeList.filter(emp => emp.name.includes(this.searchStr));
  }
  else //if no search string is provided then don't filter the array and return it as it is.
  {
    this.displayArr = this.employeeList;
  }
}

Iterate over displayArr and not original array to display.

<div *ngFor="let employee Of displayArr">
    employee.name
</div>

Thanks.

Sign up to request clarification or add additional context in comments.

Comments

1

You should save the array in an intermediate variable like so:

const filtered = [];
const unfiltered = [v1, v2, v3];

Originally copy values from unfiltered to filtered. When filtered, copy unfiltered filtered values to filtered, then revert when needed

1 Comment

Thanks for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.