Tips on programmatically filtering angular lists

Is there a way to programmatically filter an Angular list?

I'm currently working on a project where I need to filter subcategories by clicking on categories.

For example, when clicking on "Drinks," I want to display items like Coke, Fanta, Pepsi...

The filtering of subgroups works when clicked on a group, but I want to set it manually when the .html is loaded, to achieve the same effect as if the user had pressed on a category.

Below is the code snippet:

 filteredSubGroups: Group[];

 ngOnInit() {
    // Getting data from the database and console logging them
    this.groups = this._activatedRoute.snapshot.data['groups'];
    this.subGroups = this._activatedRoute.snapshot.data['subGroups'];
  }

  ngAfterViewInit() {
    this.selectedId = '78ebcad8-8cb0-4172-8cd8-bb6fb6b3bf53';
    
    this.filteredSubGroups = this.subGroups.filter(item => item.parentId === "78ebcad8-8cb0-4172-8cd8-bb6fb6b3bf53");
  }

Template below:

<li *ngFor="let subgroup of filteredSubGroups">
        <button type="button" data-toggle="" data-target="" class="btn categories-btn" (click)="getArticlesByGroupId(subgroup.id)" [class.active]="subgroup.id == selectedSubId">
            {{subgroup.title | uppercase}}
        </button>
    </li>   

However, upon running the application, the following error occurs:

ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngForOf: undefined'. Current value: 'ngForOf: [object Object],[object Object],[object Object]'. at viewDebugError (core.js:9817) at expressionChangedAfterItHasBeenCheckedError (core.js:9795) at checkBindingNoChanges (core.js:9962) at checkNoChangesNodeInline (core.js:14010) at checkNoChangesNode (core.js:13984) at debugCheckNoChangesNode (core.js:14813) at debugCheckDirectivesFn (core.js:14715) at Object.eval [as updateDirectives] (MyComponent.html:38) at Object.debugUpdateDirectives [as updateDirectives] (core.js:14697) at checkNoChangesView (core.js:13822)

Addition to original post:

https://i.sstatic.net/21n6o.png

Clicking on main categories displays subcategories:

  <li *ngFor="let group of groups;let isFirst = first" (click)="filterSubgroupsByGroupId(group.id)">
      <button type="button" data-toggle="tab" data-target="#food" class="btn xbutton-square" [class.active]="group.id == selectedId">
        <i [class]="getClass(group.image)" [innerHTML]="getUnicode(group.image)"></i>
      </button>
    </li>

I am aiming to show categories manually or programmatically upon app launch, without requiring the user to click directly on a category for visibility.

Answer №1

Replacing ngAfterViewInit with ngAfterContentInit should make it function properly.

Answer №2

Alright, let's go over the correct implementation:

1) Bring in changeDetectorReference from Angular/core 2) Add it to the constructor as shown below

constructor (cdr: ChangeDetectorReference){}

filteredSubGroups: Group[];


 ngOnInit() {
    this.groups = this._activatedRoute.snapshot.data['groups'];
    this.subGroups = this._activatedRoute.snapshot.data['subGroups'];
    this.selectedId = '78ebcad8-8cb0-4172-8cd8-bb6fb6b3bf53';
    this.filteredSubGroups = this.subGroups.filter(item => item.parentId === this.selectedId);
    this.cdr.detectChanges();
  }

With these changes, you'll have your filteredSubGroups set up before the view is initialized, preventing any errors from popping up.

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

When ng-test is executed in an Angular service, the function array.some is not found

After retrieving allUsers from the cache and initializing it, I then set the boolean value of specialUserExists based on a condition in allUsers using allUsers.some() (reference to the Array.prototype.some() method). service.ts @Injectable({ providedIn: ...

Delivering create-react-app's build files through an express server

I am trying to serve the build files of my React app on another Express application. I have copied all the static files from the build folder to the public folder inside my Express application and have set up the following code: app.use(express.static(pat ...

I am looking to send an ajax request from the themes directory's loyalty.tpl file to the LoyaltyModule.php file in PrestaShop version 1.6.1.5

How can I successfully send an ajax request from the theme file folder/loyalty.tpl to /public_html/test/modules/loyalty/LoyaltyModule.php in Prestashop 1.6.1.5? <input id="Gcash_id" name="Gcash_id" type="text" class="form-control grey" placeholder="Ent ...

Struggling to implement a Rock Paper Scissors game using HTML, CSS Bootstrap4, and JavaScript, specifically facing challenges in getting the function to select a new image

Recently, in my coding class, we were tasked with creating a program that would display images of dice and generate random numbers when the refresh button was clicked. To practice using querySelector and setAttribute, I decided to expand on the lesson by i ...

Enhancing functionality through the press of a button

I wrote a script that, upon button click, finds the closest location to your current position by searching through an array. It then locates the corresponding entry in another array and adds a number to that entry. However, I encountered a problem with app ...

Tips for implementing a jQuery mouseleave function for multiple div elements sharing the same id

I am facing an issue with my website where multiple divs share the same id. I need to implement a mouseleave function for all of these divs that have this specific id. Within my $(document).ready function, I currently have the following code... $('#m ...

Sending multiple values with the same name via AJAX using PHP

I'm facing an issue with my code: <form method="post" id="result-image" name="result-image" action="" > <?php $i=1; foreach ($data as $key => $datas) { ?> <div class="col-md-2 thumb custom-size col-lg-3 col-xs-4"> ...

Changing a single state in React results in the modification of both states simultaneously

Whenever I attempt to modify one state, I find that another state is inexplicably changing as well. I've scoured my code for the issue but can't seem to pinpoint it. What steps should I take next? Here's the snippet of code in question: impo ...

Determine the coordinates of the mouse cursor within a specific div element

Similar Questions: Determining Mouse Position Relative to a Div Getting the Mouse Position Using JavaScript in Canvas Is there a way to retrieve the mouse position within a canvas element with fixed dimensions and automatic margin? I am unable to ...

Convert the jade file to an HTML file while keeping the original file name

I'm currently attempting to configure Jade in a way that allows me to save my Jade files as HTML files while retaining the same file name. For example, I would like the file views/index.jade to be saved as dist/index.html This should apply to all ad ...

Sorting through an array of objects based on a key and value that match another object

Is it possible to filter or query an array with the following structure? [ { 'xml:id': 'Name1', sex: { '$t': 'M' }, occupation: { n: 1 ...

Choose the material and eliminate any gaps

Is there a preferred method for eliminating empty space in Material select/input fields? I am looking to ensure the field width matches the content size. https://i.stack.imgur.com/ZmgKK.png Visit https://material.angular.io/components/select/overview for ...

Navigating Paths in Real-time with Javascript - Node.js

When working with PHP, dynamic routing can be achieved by defining classes and methods like: class Route { public function homePage () { echo 'You are on the home page' } public function otherPage () { echo 'You are on so ...

Modify the ngb-timepicker formatting to output a string instead of an object

I am currently working on modifying ngb-timepicker so that it returns a string instead of an object. Right now, it is returning the following format: { "hour": 13, "minute": 30 } However, I want it to return in this format: "13:30" This is the HTM ...

The Jquery Mobile 1.4.5 virtual keyboard on the device is causing the form inputs at the bottom of the page to become hidden

I am currently working on a web app using JQuery Mobile 1.4.5. Encounter an issue that seems to be related to either the browser or JQM bug specifically when using Google Chrome in fullscreen mode on Android (v.4.4.2). Upon clicking on the Click Here!! ...

Issue: $injector:unpr Unrecognized Provider: itemslistProvider <-

I've spent several days debugging the code, but I can't seem to find a solution. I've gone through the AngularJS documentation and numerous Stack Overflow questions related to the error, yet I'm still unable to identify what's caus ...

Adding an overlay to a material UI table row: Step by step guide

My code is rendering a row in the following format: `<TableRow key={row.name} > <TableCell>{row.empId}</TableCell> <TableCell>{row.userId}</TableCell> <TableCell>{row.name}</TableCell> <TableCell>{r ...

Issues with Javascript positioning in Chrome and Safari are causing some functionality to malfunction

My Javascript script is designed to keep an image centered in the window even when the window is smaller than the image. It achieves this by adjusting the left offset of the image so that its center aligns with the center of the screen. If the window is la ...

Resolve the error message "variable is utilized prior to assignment"

Looking at the code snippet below, import { STS } from 'aws-sdk' const sts = new STS({ region: 'us-east-1' }); let accessKeyId: string let secretAccessKey: string sts.assumeRole(params, function(err, data) { if (err) { ...

Is there a way to use SCTP with Socket.io and Node.js?

I have a new project in the works, creating a web application that will utilize web sockets to provide real-time updates for users. The plan is to seamlessly transmit changes from the back-end engine. My challenge lies in Node.js not supporting SCTP sock ...