Home > Enterprise >  How to prevent filtered array from destroy in Angular?
How to prevent filtered array from destroy in Angular?

Time:05-09

I am trying to filter an array of users, but when I click on reset data is not coming back. Please guide me on how can I fix this.

  filterUsers(event:any) {
    this.users = this.users.filter(user => {
      return user.displayName.toLowerCase().includes(event.target.value.toLowerCase());
    })
  }

Any solution appreciated!

CodePudding user response:

You are assigning the result of the filter to the initial variable. Since you do not provide any other code, I'll provide a simple demo:

this.users = ['some', 'array', 'that', 'has', 'elements'];
const initialValue = ['some', 'array', 'that', 'has', 'elements'];

handleReset() {
    this.users = initialValue;
}

After having filtered your array, make sure to bind the 'handleReset' function to the reset button, which will set this.users to the initial value.

Note: .filter() method returns an array with elements that pass the filtering condition. If no elements pass the test, an empty array is returned.

For further documentation, refer to this link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#return_value

CodePudding user response:

I found a solution and I created a custom pipe to filter records. This works pretty well

Pipe

@Pipe({
  name: 'filterUser'
})

export class FilterUserPipe implements PipeTransform {
  transform(value: any, args: string) {
    return value.filter((v:any) => {
      return v.displayName.toLowerCase().includes(args.toLowerCase())
    })
  }
}

TS file

  filterUsers(event:any) {
    this.filterUser = event.target.value;
  }

HTML File

 <mat-form-field >
    <input matInput placeholder="Search Team Members..." (keyup)="filterUsers($event)">
        </mat-form-field>
<ng-container *ngFor="let user of users | filterUser:filterUser">
   <mat-option [value]="user.uid">{{user.displayName}}</mat-option>
</ng-container>

Thanku all for your suggestions.

  • Related