The onClick event handler is functioning properly, but the ngOnInit() lifecycle method is not executing the function as

I have created a filter function that is applied to elements in a list. It works when I use it on the page with a click event, like this:

<button (click)="FilterFn5()"> do </button>

However, it does not work when I put the function in the ngOnInit lifecycle hook. Here is how my ngOnInit function looks:

  ngOnInit(): void {
this.BuildingNameFilter="B"
this.BuildingRoomsFilter="2"
this.BuildingFloorFilter="0"
this.refreshBldList();
this.FilterFn5();

}

In this function:

    FilterFn5(){

  var BuildingNameFilter = this.BuildingNameFilter;
  var BuildingFloorFilter = this.BuildingFloorFilter;
  var BuildingRoomsFilter = this.BuildingRoomsFilter;

  this.BuildingList = this.BuildingListWithoutFilter.filter( (el: 
    { BuildingId:
    { toString: () => string; }; BuildingFloor: { toString: () => string; }; 
    BuildingName: { toString: () => string; }
    ApartmentRooms: { toString: () => string; };  }) =>{
     

    return el.ApartmentRooms.toString().toLowerCase().includes(
      BuildingRoomsFilter.toString().trim().toLowerCase()
      
    )
    && el.BuildingFloor.toString().toLowerCase().includes(
      BuildingFloorFilter.toString().trim().toLowerCase()
    )&&
      el.BuildingName.toString().toLowerCase().includes(
        BuildingNameFilter.toString().trim().toLowerCase()
      ) 
  });

}

The list that is being filtered is BuildingList and the function this.refreshBldList(); is used to populate the list with elements

  refreshBldList(){
this.service.getBuildingList().subscribe(data=>{
  this.BuildingList=data;
  this.BuildingListWithoutFilter=data;
});

}

Answer №1

The reason for the issue lies in the asynchronous nature of your service's get operation.

Essentially, you are attempting to invoke the FilterFn5() function immediately after calling the service to fetch the data. However, there might be a delay in retrieving the data, causing the FilterFn5 function to execute before the data is available.

To address this, I recommend adjusting your refresh function as follows:

ngOnInit(): void {
this.BuildingNameFilter="B"
this.BuildingRoomsFilter="2"
this.BuildingFloorFilter="0"
this.refreshBldList();
// this.FilterFn5(); <-- remove this line
}

// ...

refreshBldList(){
this.service.getBuildingList().subscribe(data=>{
  this.BuildingList=data;
  this.BuildingListWithoutFilter=data;
  this.FilterFn5(); // <-- add this line
});
}

Another solution is to disable the button in your HTML template until the data is received from your service:

<button [disabled]="!BuildingListWithoutFilter" (click)="FilterFn5()"> do </button>

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

Troubleshooting Problem with Angular 2 Jquery Plugin Upon Returning to Page

I am utilizing the Seriously plugin to present HTML videos on a canvas element. Everything works perfectly during the initial visit to the page, but upon returning, all the videos vanish without any console errors. import {Component, ViewChi ...

Issues with Angular's *ngIf directive not functioning correctly

Within my template, I have a block of HTML that controls the visibility of a div. <div *ngIf="csvVisible"> <p>Paragraph works</p> </div> This particular code snippet belongs to my component. export class SettingsComponent imple ...

Utilizing ngModel to map object arrays in Angular 4 within template-driven forms

Currently, I am working on a template-driven application and wanted to share my project structure with you: parent parent.component.ts parent.component.html child child.component.ts child.component.html child.ts child.ts: export class child ...

Uncover hidden mysteries within the object

I have a function that takes user input, but the argument type it receives is unknown. I need to make sure that... value is an object value contains a key named "a" function x(value: unknown){ if(value === null || typeof value !== 'obj ...

"Unable to convert object into a primitive value" error message appears on Internet Explorer

Currently working on a webpage using Angular 7. The code is functioning perfectly in Chrome, however, I am facing an Exception error while running it in IE: An issue arises: Can't convert object to primitive value (polyfills.ts) The source of the er ...

Issue: Failed to Render: Error encountered during parsing of template: Element 'mat-checkbox' is not recognized as a valid element

For the purpose of testing my component, I wrote the following code snippet: describe('Component: TestComponent', () => { let component: TestComponent; let fixture: ComponentFixture<TestComponent>; beforeEac ...

The issue with IONIC/Angular lies in its inability to properly render the JSON data retrieved

I have recently started learning IONIC/Angular and Javascript, although I do have some background in other programming languages. The issue I'm currently facing is related to fetching JSON data from an external API (I've created the API with Stra ...

The NgRX Effect is malfunctioning

Working on integrating ngrx with Angular. Authentication is successful, but facing issues with product store implementation: Organizing the project using modules: const routes: Routes = [ { path: '', redirectTo: 'home', ...

Is it necessary to have a Test Adapter in VSTS in order to include a code coverage report?

Currently, I am producing code coverage using Karma-coverage and hosting my output coverage folder on an http-server for local viewing. My question is: How can I display this report on the VSTS code coverage tab? Do I need to re-format my coverage result ...

Asynchronous execution of Angular 2 services

Currently, I am working on a project that utilizes Angular and RxJS. My approach involves creating an injectable class responsible for fetching data from a JSON source as shown below: import {Injectable, Inject} from '@angular/core'; import {Ht ...

Error: FaConfig is not provided in the NullInjector

After incorporating angular-fontawesome into my angular application using npm as instructed on GitHub, everything seemed to work smoothly during development. However, I encountered an error when trying to build for production. The initial error message I ...

Issues with ngClass in AngularAngular's ngClass feature is failing

In my ngClass condition, it looks like this: <div [ngClass]="{'alert alert-danger': alert.type == 0,'alert alert-success': alert.type == 1}" When alert.type == 1, the class is set to alert alert-success. But when alert.type = 0, th ...

Routing in Angular app breaks down after selecting a single route

I'm new to Angular and currently working with the Router module. I have a Servers component with 3 servers, and clicking on each server should open the individual server's component on the same page. However, I've encountered an issue where ...

Is Typescript capable of converting ES6 code to ES5 during transpilation?

Currently, I'm in the process of developing an application utilizing Angular 2 and TypeScript. My goal is to incorporate a JavaScript method, specifically 'filter' for arrays, that is compatible with IE 11+, Chrome 45+, and other similar bro ...

Leveraging the power of APIs to bring in the Chicago Art Institute into a React TypeScript

Struggling to import a list of image details from the Chicago Art Institute into my React application. I need help understanding APIs, so a detailed answer would be appreciated. I have the code for the image list but can't figure out how to make it wo ...

Developing interconnected dynamic components in Angular

Can you help me figure out how to create nested dynamic components while maintaining the parent-child relationship? For instance, if I have data structured like this: - A --A.1 --A.2 -B --B.1 -C I want to build components that reflect this structure, su ...

Create a new WebSocket package for Node.js that allows for segregating connections into

I am currently exploring ways to implement a feature similar to "rooms" using the npm 'ws' package, inspired by how rooms function in socket.io. I want to avoid using socket.io, but I am faced with the challenge of retrieving user/room informatio ...

Issues with Cognito integration in setting up a Cloudfront Distribution for hosting static content on S3

I've been facing an issue with my S3 website behind a CloudFront distribution when trying to authenticate with Cognito. Everything works perfectly when testing my Angular app locally with Callback URL and Sign out URL set to localhost:4200/. https:// ...

Angular 2: Executing a function after ngFor has completed

Within Angular 1, I crafted a personalized directive called "repeater-ready" to pair with ng-repeat for triggering a callback method upon completion of an iteration: if ($scope.$last === true) { $timeout(() => { $scope.$parent.$parent.$ ...

What is the best way to handle various sections with changing structures within a complex form using react-hook-form?

I am working on a complex form that has sections A, B, and C, each of which can be in shape A1 or A2, B1 or B2, C1, or C2. Users are required to fill out settings based on whether the section is set to "advanced" or "basic". I want users to submit the enti ...