Ways to update a component upon becoming visible in Angular

Within my Angular 4.3.0 project, the header, left panel, and right panels are initially hidden on the login page until a successful login occurs. However, once they become visible, the data is not pre-loaded properly causing errors due to the ngOnInit method being called when the components first load. Is there a way to ensure that the components are loaded or refreshed upon successful login?

Below is the code snippet from App-Component.html:

<loading-bar color="#FF0000" [height]="3" [animationTime]="0.3" [runInterval]="100" [progress]="0"></loading-bar>
<div class="app app-header-fixed" value="test">
    <app-header *ngIf="header"></app-header>

    <app-left-menu *ngIf="leftmenu"></app-left-menu>
    <div id="content" class="app-content plain_wraper" role="main">
        <router-outlet></router-outlet>
    </div>

    <app-right-menu *ngIf="rightmenu"></app-right-menu>

</div>

For instance, in the app-header component, the ngOnInit method fetches the user's profile like this:

this.userProfile = this.userServ.getUserProfile();

However, this causes errors as the profile data doesn't load correctly. Is there a way to ensure that the profile data loads only when the component becomes visible?

Would subscribing to the visibility parameters and loading the profile data once the component is visible be a suitable solution?

Thank you!

Answer №1

In my opinion, ngOnInit should not be classified as a method. It is actually a life-cycle hook where you can call methods.

Based on the context, it seems like initializing data in the ngAfterViewInit hook would be more appropriate. So you could do something like this:

ngAfterViewInit(){
  this.userProfile = this.userService.getUserProfile();
}

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

The Javascript Node class encountered an error: X has not been defined

I have a class that looks like this: const MongoClient = require("mongodb").MongoClient; const ConnectionDetails = require("./ConnectionDetails").ConnectionDetails; const Recipe = require("./recipe").Recipe; var ObjectId = req ...

jQuery eliminates initial div just a single time

Here is a function I have created: function removeDiv() { var topmost = jQuery('.xx'); var totContent = topmost.find('.zz').length; var $target = jQuery('.xx').find('.zz').eq(0); if(totCont ...

Understanding Typings in Typescript

Just delving into the world of Angular2 and finding it quite exciting, but running into a roadblock with Typings. The concept is not clear to me - how do I utilize them and what purpose do they serve? Different sources suggest different approaches, some me ...

After a loop, a TypeScript promise will be returned

I am facing a challenge in returning after all calls to an external service are completed. My current code processes through the for loop too quickly and returns prematurely. Using 'promise.all' is not an option here since I require values obtain ...

Issue TS2345: Cannot use type 'Product | undefined' as an argument for type 'Product[] | PromiseLike<Product[]>'

Having trouble retrieving my products using their IDs You can find the code here ...

What is the best way to deactivate a button using AngularJS?

$scope.date = moment(currentDate); $scope.date1 = moment(currentDate).add(-1, 'days'); function checkDate(){ if ($scope.date > $scope.date1) { return true; } else{ return false; } }; checkDate(); ...

What is the best approach to implement runtime configuration in Angular 15, ensuring that values can be provided in AppModule imports as well?

After two days of brainstorming, I am still struggling to figure out a way to read a config.json file located in my assets folder. I attempted to read this file during the bootstrapping process in main.ts so that I could use the values in my AppModule lik ...

Every time I attempt to run "npm install" on Visual Studio Code, I encounter an error

Every time I try to run npm install, I encounter this error. My node version is 18.9.1 and I have exhausted all possible solutions. Any help would be greatly appreciated. '''npm ERR! code ENOENT npm ERR! syscall open npm ERR! path C:\Us ...

Broaden material-ui component functionality with forwardRef and typescript

To enhance a material-ui component with typescript, I have the javascript code provided in this link. import Button from "@material-ui/core/Button"; const RegularButton = React.forwardRef((props, ref) => { return ( <B ...

Identifying when a system window covers an iframe

After watching a fascinating YouTube video (https://www.youtube.com/watch?v=TzPq5_kCfow), I became intrigued by how certain features demonstrated in the video could be implemented using JavaScript. One specific question that arose for me was how one can d ...

Enhancing User Experience with JQuery Pagination and Efficient Data Loading

I am looking to implement pagination for data retrieved from a database. The information needs to be displayed in a 4x4 table format. For the remaining data that doesn't fit in the initial view, I want to enable pagination with AJAX functionality so ...

Condensing an Array of Objects into a solitary result

Hey there, I'm currently exploring the most efficient method to accomplish a task. The data I am dealing with looks something like this: [ { name: 'email.delivered', programme: 'Email One', timestamp: 2022-03-24T18: ...

What steps can be taken to choose a particular class when multiple classes share the same name?

Imagine having a table layout like this: <table class="first-table" border="1" width="400px"> <tr> <td><?php echo $row_cond['title']; ?></td> <td><a class="more" href="#" onClick="slideup() ...

What is the method to identify the test case name as passed or failed in Puppeteer?

I am currently working on integrating the puppeteer-jest test framework with TestRail using TestRail API. To accomplish this task, I need to identify which tests have failed and which tests have passed. Despite searching through the official GitHub Reposi ...

Displaying an array in an Ionic HTML template without using the *ng

Is there a way to retrieve data from an Array in Ionic 3 without relying on ngFor? Here's an example that currently works: <ion-item-sliding *ngFor="let user of users"> <ion-item> <ion-grid> <ion-row> < ...

consolidating express routes in one consolidated file

I am attempting to consolidate routes into a single file using app.use app.js import express from 'express' import testRouter from 'testRouter' const app = express() app.use('/testRouter', testRouter) app.listen(3000) tes ...

The type '{}' cannot be assigned to type 'IntrinsicAttributes & FieldsProp'. This error message is unclear and difficult to understand

"The error message "Type '{}' is not assignable to type 'IntrinsicAttributes & FieldsProp'.ts(2322)" is difficult to understand. When I encountered this typeerror" import { useState } from "react"; import { Card } fr ...

Enhance your Typescript code by incorporating typing for response objects that include both index signatures and key-value pairs

I am grappling with how to properly incorporate typescript typings for the response object received from a backend service: { de49e137f2423457985ec6794536cd3c: { productId: 'de49e137f2423457985ec6794536cd3c', title: 'ite ...

Including onMouseUp and onMouseDown events within a JavaScript function

I am experiencing an issue with a div that contains an input image with the ID of "Area-Light". I am attempting to pass the ID of the input image to a function. Although event handlers can be directly added inside the input tag, I prefer to do it within ...

Simulated FileList for Angular 5 App Unit Testing

Imitation FileList In my pursuit of writing a unit test (Angular5), I have encountered the need for a FileList. Despite researching extensively, I have been unable to uncover any clues or solutions. I am starting to question whether this is even feasible ...