Which is the best place to initialize variables in Angular: Constructor, Declaration, or ngOnInit, including observables?

Here is an Angular component code snippet:

export class ListComponent implements OnInit {

  showComments: boolean = false;

  posts$: Observable<PostModel[]>;

  constructor(private postService: PostService) { }

  ngOnInit() {

    this.posts$ = this.getPosts();

  }

  getPosts(): Observable<PostModel[]> {

    return this.postService.getRecentPosts();

  }

}

Is it necessary to define posts$ within the constructor?

What should be the default value for showComments? Is it acceptable to define it inside ngOnInit as well?

If not, when is the appropriate time to use the ngOnInit method?

Answer №1

Utilizing the Constructor in Angular: When working with Angular, the constructor serves as a way to inject dependencies into the component class. It is advisable to keep the constructor straightforward and succinct.

Applying the ngOnInit() Method in Angular: In Angular, the ngOnInit() method is invoked after the component DOM has been fully created. Constructors are typically utilized to inject necessary dependencies and process input bindings.

While it's customary to use ngOnInit for tasks that do not rely on DI, DOM operations, or input bindings, it can still be effectively employed for such purposes.

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

Ways to extract information from a database using a parameter

I am currently working with angular cli version 8.1.0 and I have a requirement to pass parameters in the URL and retrieve data from a PHP MySQL database. On the PHP side, everything is functioning correctly and the URL looks like this: http://localhost/rep ...

What causes the "This page isn't responding" error to pop up in Edge and Chrome browsers while attempting to perform consecutive tasks in a web application built with Angular 8?

Trouble with Page Loading Whenever this error occurs, I find myself unable to perform any activities on that page. The only solution is to close the tab and open a new one. My current code allows me to navigate through an array list (Next and Previous) us ...

Angular 2: Firebase fails to provide a response

I am facing an issue with retrieving data from my Firebase using Angular 2 and TypeScript. While console.log() works, I am unable to return the value into a variable. My DataService looks like this: import {Injectable} from "angular2/core"; import ' ...

I'd like to know how to retrieve a total count of all the documents within a Firebase collection using Angular

My code currently fetches documents from a collection, but it's only bringing back 15 at a time (from what I can gather). This is causing an issue as I need to accurately determine the total number of documents in the collection for a program I'm ...

Ways to dynamically change values within a single Angular component when making multiple selections using mat-select

Imagine you're developing a cutting-edge pizza ordering application complete with a MenuComponent that showcases all the delicious menu items offered by the restaurant. Each item is presented as a unique card displaying all the essential information. ...

The Angular APP_INITIALIZER provider is encountering an issue where one injected service is being passed as undefined, while the rest are

One of my injected services is returning as undefined in my provider, despite both services running before the provider. Any help or insight would be greatly appreciated. Below is a snippet of my code from AppModule: @NgModule({ declarations: [ // ...

Create a union type by utilizing indices of an array type

For instance: type BasicTheme = { name: 'basic'; colors: [string, string]; }; type AdvancedTheme = { name: 'advanced'; colors: [string, string, string, string]; }; type MainColor = ???; // 'main-1' | 'main-2&apo ...

The struggle continues in attempting to adjust Angular Material 2 dialog positioning using MdDialogConfig

Does anyone know how to adjust the position of an MdDialog? openDialog() { let config = new MdDialogConfig(); config.height = '15px'; config.position.left = '5px'; let dialogRef = this.dialog.open(BasicAlertDialog, config); dialogRef. ...

Possible undefined object in React Redux

I'm encountering a Typescript issue where Redux object I am utilizing is potentially undefined, even though I have not specified its type as potentially being undefined or set it to be undefined anywhere in my code. /redux/globalSettings/actions.ts ...

Is there a way to retrieve the chosen value from an ion-alert radio alert?

async showAlertRadio(heading:string){ const alert = await this.alertCtrl.create({ header: heading, inputs :[ { name : 'Radio 1', type: 'radio', label: 'Radio 1', ...

Angular error: Trying to access the sort property of an undefined value

I am currently working on creating a sorting function and pipe for a table. I found guidance on how to do this by following a tutorial at this link, and here is the plunker example. In the example, the table header should be clickable to trigger the sort() ...

Exploring Angular 4's capability: Incorporating data from Http Post Response into a .js file or highchart

I'm a beginner with Angular 4. I'm trying to create a dashboard that pulls data from an Http Post Response and I want to use this data to create a Chart (Highchart). I have successfully received the response in the console.log and formatted it i ...

Angular problem: Cannot connect to 'formGroup' as it is not a recognized property of 'form'

Struggling to set up a simple form in Angular consisting of a label and an input field. Despite following suggestions to import FormsModule and ReactiveFormsModule, I'm still encountering errors as mentioned numerous times on StackOverflow. Here&apos ...

Creating dynamic HTML in Angular 2 can be achieved by utilizing directives, data

I am interested in building an accordion feature in angular2 without needing to duplicate the structure each time it is used. Similar to how we can create plugins in jQuery and include HTML code, I would like to find a way to achieve this in Angular2. Ca ...

"Exploring the capabilities of Rxjs ReplaySubject and its usage with the

Is it possible to utilize the pairwise() method with a ReplaySubject instead of a BehaviorSubject when working with the first emitted value? Typically, with a BehaviorSubject, I can set the initial value in the constructor allowing pairwise() to function ...

The type '{ children: ReactNode; }' does not share any properties with the type 'IntrinsicAtrributes'

I have explored several discussions on the topic but none of them have provided a solution to my issue. My objective is to develop a reusable Typography component that resembles the following structure: import React from 'react' import type { Ty ...

Preserve information from apps in ionic2

Is there a way to store the data from services in Ionic2 so that it doesn't need to be called every time the user navigates to the view? public getUpcomingShoots(){ var json = JSON.stringify({ }); var headers = new Headers(); ...

Remove validators from an Angular formArray

Is there a way to reset validators for the formArray within my formGroup? Check out my StackBlitz for reference. .ts this.createEstimation = this.fb.group({ name: ['', Validators.required], surname: ['', Validators.required], ca ...

Translate the pipe based on the language specified in the URL using Angular 2

In my Angular2 application, I have a translate pipe. The LanguageComponent is the parent component for all others in which it reads the URL to determine the language and then adds it to the translate service that the pipe uses: { path: ':lang', ...

Preventing recursive updates or endless loops while utilizing React's useMemo function

I'm currently working on updating a react table data with asynchronous data. In my initial attempt, the memo function doesn't seem to be called: export const DataTableComponent = (props: State) => { let internal_data: TableData[] = []; ...