Best Practices for Initializing Angular Directives

When it comes to initializing complex properties like observables, form-related elements, or synchronous code that requires time and resources, the question arises: Where is the best place to do this?

Consider having the same component in two different versions:

@Component({})
class ExampleComponent {
  // Initialize in class body or constructor
  users$ = this.store.select(selectUsers);
  constructor(
    protected store: Store<any>,
  ) { }
}

@Component({})
class ExampleComponent implements OnInit {
  users$: Observable<User[]>;
  constructor(
    protected store: Store<any>,
  ) { }
  // Initialize on component init
  ngOnInit() {
    this.users$ = this.store.select(selectUsers);
  }
}

Which version is more efficient? What are the advantages and disadvantages of each approach?

Answer №1

During the initialization phase, it is recommended to send requests using the ngOnInit life cycle event handler. This is especially useful when you have @Input parameters that need to be passed to the component and used in the requests - as these parameters are only available during the ngOnInit.

If your component does not receive any @Input parameters and is independent of other components, you can opt for the first version. However, even in this scenario (without parameters), it is a common practice to place requests within the ngOnInit. It is advisable to follow a consistent style and utilize the second version. In terms of efficiency, both options are similar - the variable is created and assigned a value at the same time when calling this.store.select(selectUsers).

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

Exploring Rxjs in Angular 2: Curious about the functionality of the code snippet below

Currently, I am in the process of learning Angular2. While following a programming course, I came across the code snippet provided below in the exercise files. I am struggling to grasp the purpose and function of the statement ".do(this.toggleLogState.bind ...

Ways to Conceal Information in Angular2

On my website, I have a layout with three tabs. In the third tab, I've implemented an ng-select tag. My goal is to only display the 1st ng-select tag initially, while keeping the other two hidden until the user selects data in the 1st tag. For referen ...

Is there a way to designate the current tab in PrimeNG's tabMenu as active?

Can someone please explain where I need to declare activeIndex variable and how to properly use it? Here is my code in the HTML file: <p-tabMenu [model]="tabMenuItems"></p-tabMenu> And here is the TypeScript file: tabMenuItems: MenuItem[]; ...

Error: Trying to dispatch from an undefined property in Angular and Redux

In the process of developing a Shopping app using Angular + Redux, I encountered an issue. When attempting to trigger the "ADD_PRODUCT" action on click through a dispatcher function, I keep running into the error message: ERROR TypeError: Cannot read prop ...

Ensure that MatTable displays newly added rows

A snippet of an Angular component I am working on shows how I am creating a table: import {Component, Inject} from '@angular/core'; import {MatTableDataSource} from '@angular/material'; import {ChromeDataService} from "../../../../shar ...

Using both ngIf and ngFor in the same Angular2 template can lead to unexpected behavior and errors in the application

<ng-container *ngIf="selectedPlayer; else infoText"> <div *ngFor="let playerEL of players"> [playersLIST]="playerEL" (playerSelected)="onPlayerChosen(playerEL)"> </div> </ng-container> < ...

What is the best approach to re-establish a websocket connection in TypeScript?

Encountering an issue when trying to add a "retry()" method: ERROR in src/app/films.service.ts(28,20): error TS2339: Property 'retry' does not exist on type 'WebSocketSubject'. this.wsSubject.retry().subscribe( (msg) => this. ...

Creating a blueprint for an object that inherits from another interface

I am looking to create an interface that includes unknown properties for one object, while also extending it with known properties from another interface. Here is my attempt: public async dispatchMessage(): Promise<{} extends IHasResponseFormat> I ...

React's setState is not reflecting the changes made to the reduced array

I am currently working on a custom component that consists of two select lists with buttons to move options from the available list to the selected list. The issue I am facing is that even though the elements are successfully added to the target list, they ...

What methods can be used to conceal internal-only modules from users and consumers of a module?

I have been creating various node packages utilizing ES Modules. Within these packages, some modules are meant to be utilized externally by other packages, while certain module exports are intended for internal use only within my own package. From my unde ...

Failure of Gulp Dest() to Generate File Output

Struggling to make gulp.dest output correctly. I'm aiming to output to the root of an ASP.NET Core project that I'm repurposing for TypeScript development. Any guidance on how to achieve this would be greatly appreciated. Below is the current con ...

Is it possible to convert a radio input value from a string to a number in Angular?

My radio button list displays the days of the week, with their corresponding values as weekday IDs in Number format. However, when I use Angular to bind these values in my form group, they are transformed into strings. const currentHour = moment('08: ...

Angular 8 UI not displaying mockAPI data as expected

My mockAPI is successfully fetching the data, but the json response structure is quite complex. It looks something like this: [ { "planList": [ // plan details here ] } ] Everything in the UI is displaying correctly, except ...

Accessing property values from a map in Angular

Is there a way to retrieve a property from a map and display it in a table using Angular? I keep getting [object Object] when I try to display it. Even using property.first doesn't show anything. //model export interface UserModel { room: Map ...

Issues with displaying rows and/or elements in Angular 8 DexExtreme dx-list component

After several debugging attempts, I am almost certain that the data transmission from the controller to the client side view model through the REST API connection is correct. The dx-list we are utilizing seems to be detecting the correct number of rows bas ...

The Angular/Typescript framework encountered an issue when trying to locate a differ that can handle an object of type 'object'. NgFor is limited to binding with Iterables like Arrays and is not compatible with plain objects

I am currently utilizing Angular for my project. I am attempting to call an API to fetch data from it, but I keep encountering this error: core.js:4352 ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object&ap ...

Unable to modify the date input format in Angular when utilizing the input type date

I am currently working with angular 10 and bootstrap 4. I am trying to update the date format in an input field from (dd/mm/yyyy) to DD/MM/YYYY, but I am facing issues. Below is my angular code: <input type="date" id="controlKey" cl ...

When attempting to compile my Angular project using the command ng build --prod, I encountered a server error stating that the document

Everything was running smoothly when I was working on my local machine, but once I uploaded the files generated from ng build --prod to the server, a problem arose. Now, whenever I try to route via a button in my components, an error appears. When I clic ...

How to Position Logo in the Center of MUI AppBar in React

I've been struggling to center align the logo in the AppBar. I can't seem to get the logo to be centered both vertically and horizontally on its own. Here is my code from AppBar.tsx: import * as React from 'react'; import { styled, useT ...

Leveraging cloud functions on Firebase for maximum efficiency

Question: Do you require a backend language when using Firebase Cloud Functions, or can TypeScript alone suffice for coding tasks like creating a matchmaking system? Response: There seems to be some uncertainty on the matter even from ChatGPT himself. Is ...