Is it possible to make *ngIf in Angular run just one time?

I am facing a minor issue - I need to implement roles validation in my Angular application. The structure of the application consists of pages, each containing multiple components. User privileges are assigned at the component level, making it necessary to use *ngIf for validation on each individual component:

     <results-component 
          *ngIf="auth.hasPermission('driver_productivity')"
          [format] = "driver_productivityFormat" 
          [IsFullWidth] = "IsFullWidth"
          (customEvent)="showPrint($event)">
     </results-component>

auth.service.ts:

hasPermission(permissionName){
if (!this.tokenPayload){
  this.getToken().subscribe(t=>{this.tokenPayload=decode(t.getValue())});
  if (this.tokenPayload.roles && this.tokenPayload.roles.length>0 ){
    this.permissions={};
    for (let i=0;i<this.tokenPayload.roles.length;i++){
      this.permissions[this.tokenPayload.roles[i]]=true
    }
  }
}
return this.permissions[permissionName]

}

However, applying this validation for multiple components on a page has led to excessive processing time and is proving to be an inefficient solution.

[Violation] 'setInterval' handler took 150ms zone.js:1755 [Violation] 'click' handler took 318ms zone.js:2279 [Violation] 'requestAnimationFrame' handler took 84ms zone.js:1755 [Violation] 'click' handler took 261ms

Is there a way to optimize the *ngIf directive to run only once when the component is initially loaded?

Answer №1

How can I ensure that *ngIf is only executed once when the component initially loads?

To achieve this, simply relocate the relevant logic to the ngOnInit(...) method within your component. This way, it will only be triggered once upon the component's initial load.

Answer №2

If you want to streamline your code, you have the option of transferring your logic to ngOnInit as suggested earlier, or you could opt to create a pipe. Pipes have the advantage of being memoized, meaning that the internal logic will only be re-executed when there is a change in the input.

I have put together a demonstration on Stackblitz to illustrate this concept.

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

Use a pipe to show the content of the md-input

In my Angular 2 Material application, I have a form that includes a price input: <md-input [(ngModel)]="price" placeholder="Price"> </md-input>{{price|customCurrency}} This input field uses a custom version of the CurrencyPipe which you c ...

Angular9 integrated with Firebase to enhance the capabilities of

I am facing an issue with displaying a specific element from the database. //component.html <section class="firee"> <figure class="snip1208"> <div *ngFor="let scholarship of scholarships" > <h3>{{scholarshi ...

Top method for retrieving CSS variable in a customized Angular directive

I have a question regarding the process of converting the statement below to Angular's renderer2: this.elementRef.nativeElement.style.setProperty( '--primary-color ' , '#455363' ) The above statement modifies a CSS variable in the ...

JavaScript method of retrieving an object inside an array nested within another object via multer

Below is my custom multer function to handle file uploads - const storage = multer.diskStorage({ destination: (req, file, callback) => { let type = req.params.type; let path = `./data/${type}`; fs.mkdirsSync(path); callback(null, path) ...

ngx-infinite-scroll event fails to trigger upon scrolling to the end

I am currently facing an issue while trying to implement infinite scroll using ngx-infinite-scroll in an Angular 4 application. Despite following the documentation and configuring the height of the element while setting scrollWindow to false, the trigger i ...

Angular 2 - Constructing dates in constructor - Error: Type 'Date' cannot be assigned to type 'string'

In my attempt to generate a fresh date object for an ngx-chart by referencing this specific example, I came across the following code snippet: constructor() { this.data = this.multi.map(group => { group.series = group.series.map(dataItem =& ...

The TypeScript interface is incorrectly extending another interface, causing a compatibility issue with the 'then' property types

Before casting a downvote without reason, kindly take a moment to check my profile or ask for clarification. Your input, suggestions, and edits are valuable in improving the question further. I've scoured Stack Overflow and searched extensively online ...

Managing errors when dealing with Observables that are being replayed and have a long lifespan

StackBlitz: https://stackblitz.com/edit/angular-ivy-s8mzka I've developed an Angular template that utilizes the `async` pipe to subscribe to an Observable. This Observable is generated by: Subscription to an NgRx Store Selector (which provides sele ...

Distinguishing between Angular 4's componentInstance and debugElement.componentInstance

Recently, I was reading through the documentation on this site: https://angular.io/guide/testing component = fixture.debugElement.componentInstance component = fixture.componentInstance However, I am still unclear about the distinction between these two. ...

The browser is failing to load the login page, however, the method is functioning properly when accessed through Postman

I am facing an issue in my angular project with the login component - it is not loading the login page and instead showing a HTTP ERROR 401. Curiously, when I try to log in using Postman, everything works perfectly fine. However, I can't seem to figu ...

creating a duplicate of a class instance in TypeScript

Struggling to replicate an instance in typescript. Tried using jQuery.extend(true, {}, instance) but methods are not copied Any assistance on this issue would be highly appreciated ...

An error was encountered while trying to use the 'export' token in lodash-es that was not

Transitioning from lodash to lodash-es in my TypeScript project has been a challenge. After installing lodash-es and @types/lodash-es, I encountered an error when compiling my project using webpack: C:\..\node_modules\lodash-es\lodash. ...

The component I created is not visible on the index page

I am new to Angular and I am trying to create a simple component, but I am facing an issue where my component is not showing up on the index page. Can someone please help me with this? Here is my component named "List.Component.ts": import { Component } ...

Troubleshooting Rxjs issues related to a chain of operators

Encountering an issue with the switchMap operator: @Injectable() export class AvailableStoreTypesLoadedEffect { constructor(private actions$: Actions, private service: AvailableService) { } @Effect() AvailableStoreTypesLoadedEffect$ = this.a ...

Troubleshooting Angular Toaster issues with TypeScript

After downloading the angular-toaster.d.ts file from Nuget and setting up a notification service, everything seems error-free, but the notification service is not functioning as expected. export class notificationService { constructor(private toaster ...

Node Express and Typescript app are failing to execute new endpoints

Hello, I'm currently diving into Node express and working on a simple CRUD app for pets. So far, I've successfully created 2 endpoints that are functioning properly. However, whenever I try to add a new endpoint, Postman fails to recognize it, g ...

Angular's response was not accurate

Just dipping my toes into nodejs & angular and here's my restAPI function: exports.getPlanningStages = async (req, res, next) => { const currentPage = req.query.page || 1; const perPage = 2; try { const totalItems = await Planningstage. ...

Ensure that type checking is applied exclusively to the properties of an object, and define the keys as constants

Defining constants with predefined keys in typescript can be confusing at times. Let's walk through an example: // suppose we have this object const MY_LIB = { id_1: {foo: 'foo', bar: 'bar'}, id_2: {foo: 'foo', ba ...

How to properly display an Angular Template expression in an Angular HTML Component Template without any issues?

When writing documentation within an Angular App, is there a way to prevent code from executing and instead display it as regular text? {{ date | date :'short'}} Many sources suggest using a span element to achieve this: <span class="pun"&g ...

Encountering an Uncaught Error: MyModule type lacks the 'ɵmod' property

I am currently working on developing a custom module to store all my UI components. It is essential that this module is compatible with Angular 10 and above. Here is the package.json file for my library: { "name": "myLibModule", &qu ...