Refreshing list after cancelling search not working in Ionic 3

Is there a more efficient way for me to phrase this? I've integrated a search bar in Ionic and it appears to be functioning correctly. However, when I click the cancel icon on the search bar, the lists/contents do not revert back.

This is my.html

<ion-header>
    <ion-navbar >
        <ion-title>Worship and Fellowship</ion-title>
    </ion-navbar>
    <ion-searchbar 
         (ionInput)="getItems($event)">
    </ion-searchbar>
</ion-header>

<ion-content padding>
    <ion-list inset>
        <ion-item *ngFor="let lesson of lessons; index as i;" slice:0:10>
            <h4 (click)="loadLesson(lesson)" tapable>{{ lesson.title | uppercase }}</h4>
        </ion-item>
    </ion-list>
</ion-content>

This is my .ts

@IonicPage()
@Component({
  selector: 'page-section1',
  templateUrl: 'section1.html',
})
export class Section1Page {
  ID:number;
  lessons:Lessons[];

  constructor(public navCtrl: NavController, public navParams: NavParams, private cdata: ChorusdataProvider) {
    this.cdata.getData().subscribe(lists => {
      console.log("lessons are here", lists['section1']);
      this.lessons = lists['section1'];
    });
   }

  initializeItems() {
    this.lessons = this.lessons;
  }
  
  getItems(ev) {
    // Reset items back to all original items
    this.initializeItems();

    // Set val to the value of the event target
    var val = ev.target.value;

    // If the value is an empty string don't filter the items
    if (val && val.trim() != '') {
      this.lessons = this.lessons.filter((lesson) => {
        return (lesson.title.toString().toLowerCase().indexOf(val.toLowerCase()) > -1);
      })
    }
  }    
}

I can't figure out what I'm doing wrong. When someone uses the search bar and taps the cancel icon, the content list should refresh to its original state like a normal search bar. What am I missing?

Answer №1

It appears that in your situation, you are modifying the original list directly instead of preserving its state by creating a copy.

Consider utilizing a method that involves taking a "snapshot" of the list, and when resetting it, avoid simply assigning another array as it will just be passed by reference.

@IonicPage()
@Component({
    selector: 'page-section1',
    templateUrl: 'section1.html',
})
export class Section1Page {

    ID: number;
    // Contains the searchable list:
    lessons: Lessons[];
    // Snapshot of the original list:
    lessonsSnapshot: Lessons[];

    constructor(public navCtrl: NavController, public navParams: NavParams, private cdata: ChorusdataProvider) {
        this.cdata.getData().subscribe(lists => {
            console.log("lessons are here", lists['section1']);
            // Creating a snapshot:
            this.lessonsSnapshot = lists['section1'];
            // Populating the view:
            this.lessons = lists['section1'];
        });

    }


    initializeItems() {
        // Use the spread operator to create a new array based on the snapshot
        this.lessons = [...this.lessonsSnapshot];
    }

    getItems(ev) {
        // Reset items back to all of the items
        this.initializeItems();

        // Set val to the value of the event target
        var val = ev.target.value;

        // If the value is an empty string, do not filter the items
        if (val && val.trim() != '') {
            this.lessons = this.lessons.filter((lesson) => {
                return (lesson.title.toString().toLowerCase().indexOf(val.toLowerCase()) > -1);
            })
        }
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

IntelliJ is indicating a typescript error related to react-bootstrap-table-next

Working with react-bootstrap-table-next (also known as react-bootstrap-table2) has been causing a Typescript error in my IntelliJ environment, specifically on the validator field within my column definition. Despite trying various solutions, such as adding ...

Trouble with Firebase Setup in Ionic 4+ Web Application

I'm currently trying to establish a connection between my ionic application and Firebase for data storage, retrieval, and authentication. Despite using the npm package with npm install firebase, I encountered an error message that reads: > [email& ...

Refreshing the page does not trigger Angular callHooks

Encountering an issue with the proper invocation of F5 button or directive call URL from the address bar resulting in ngOnInit not being triggered correctly. Using a debugger to analyze the situation, it was noticed that callHook is not initiated after ngO ...

Unfortunately, the package "error-ex" could not be found when attempting to access it through the npm registry

I am encountering an issue while trying to install npm package dependencies in my Angular application. The error message I receive is related to "error-ex@^1.2.0". Can anyone provide guidance on how to resolve this problem? npm ERR! code E404 npm ERR! 404 ...

The Angular Universal client side appears to be inactive

My server-side rendered application is up and running, but I'm encountering an issue where the client-side functionality seems to be missing. Despite the routes rendering properly, none of the click events or console logs are working on the client sid ...

When Typescript calls the toString method on a Function, it produces unexpected characters like "path_1, (0, promises.writeFile)"

I'm currently attempting to convert a function into a string for transmission to a worker thread for execution. However, when imported code is included, the resulting string contains strange characters. import { HttpStatus } from '@nestjs/common& ...

Cross-origin request error persists despite configuring headers on the server. Unable to successfully relocate image to designated directory on the server

I am encountering a CORS error specifically when sending delete requests from Angular to Laravel. Additionally, I am facing issues with moving car model images to the directory during posting, resulting in errors. I have implemented a CORS middleware and a ...

Updating the array in React state does not work properly

Update: Visit the Snack Expo for the latest version. I have a page that displays a list. When I click on a Delete button, my goal is to remove the item with a specific id from the list. The code snippet is shown below: import { useState, memo, useCallbac ...

How can Typescript limit the global availability of exported items?

Imagine a TypeScript folder structure like this: index.ts login/ --index.ts --util.ts registration/ --index.ts --util.ts Is there a way to limit the exports (namespaces) of the modules to within the folders? For instance, if both util.ts modules e ...

The paths configuration in tsconfig.app.json is not functioning as anticipated

Working with Angular to develop my website has been a rewarding experience. I am currently faced with the task of setting a BASE_API for my project, depending on whether it is in prod or dev> mode. To accomplish this, I have made necessary modifications ...

How to link Array with Observable in Angular2 Typescript without using .interval()

Is it possible to achieve the same functionality without using the "interval()" method? I would like to link an array to an observable, and update the array as well as have the observable monitor the changes. If this approach is feasible, how can we inco ...

Support for integrating Angular 2 with SAP's backend system

Curious to learn about the compatibility of Angular version 2 with SAP as a backend database and would appreciate any insight into the advantages and disadvantages of using these together. ...

ReactJS Typescript Material UI Modular Dialog Component

Hello, I need help with creating a Reusable Material UI Modal Dialog component. It's supposed to show up whenever I click the button on any component, but for some reason, it's not displaying. Here's the code snippet: *********************TH ...

The functionality of ellipsis, which consists of three dots, allows the text to expand

I am trying to implement a feature where the extra text is represented by three dots (...) as an ellipsis, and upon clicking the dots, the text should expand and contract. However, the current code only contracts the text and does not expand it upon clicki ...

Is there a way to apply a consistent style to all the fields of an object at once?

I have a formatting object named typography that includes various styles. One common issue I've encountered is that the line-height property is consistently set to 135%. Anticipating that this might change in the future, I am looking for a way to cent ...

No data being displayed or returned from API when using async await

My Ionic 6 + Angular 14 application is currently facing an issue with displaying data retrieved from an API... I have implemented a service to fetch the data from the API and then called this service in the component. The app compiles without any errors a ...

Using TypeScript to destructure by providing types

I encountered an issue while trying to destructure some code. The error message Property 'name' does not exist on type '{}'. is appearing. I thought about using let user:any = {}; as a workaround, but that goes against the eslint rule o ...

Is it possible to only select items within the current PageSize in Mat-Table?

I am currently developing a table with pagination that involves performing certain actions based on an array of selected checkboxes. I have referred to the documentation and everything seems to be working fine when it comes to selecting individual rows or ...

When calling a function within a for loop, the function receives the final value instead of iterating through the sequence

I need assistance with setting unique names for objects in an array. I have the following setup: this.array = [{name: null}, {name: null}, {name: null}] Along with a list of reserved names: this.reserved = ["name2", "name3"] My goal is to loop through th ...

The array is not being spliced in the DOM, however, it is being spliced in the console - Ionic 2+/Angular

My scenario involves a dynamic array filled with items and values. The goal is to remove an item from the view list when a user clicks a button on that particular item. I'm struggling to identify why this functionality isn't working as expected. ...