Navigating the murky waters of Angular 2 component class methods: Should they be public or

I find it challenging to determine which methods should be designated as private and which should be public within a component class.

It's generally straightforward in a service to determine whether a method should be public or private, for example:

export class MyServiceClass {
  private _cache = {}; // this value is private and should not be accessed externally
  public accessCache(){ // this is a public API method
    return this._cache;
  }
  public setCache(newVal){
     this._cache = newVal;
  }
}

Following this reasoning, all methods within a component should be private because none of them should be exposed outside of the class. (based on this post stating that a component and its view are considered one entity)

export class MyComponent {      
  private _getRandomNumbers(){ // this is solely used within the view
    /*..*/
  }
}

While this may not pose a significant issue, a video suggests that only public methods in a component should be unit tested. However, under the above logic, there seems to be no justification for having public methods in a component class. Despite this, there are still methods that are worth testing, especially those utilized within the view. This has left me perplexed about the distinction between private and public methods in the angular context.

So, the question I pose is simple:

which methods within components should be designated as public and private.

Answer №1

When working with Component Class, my recommendation would be to set everything as public (since if no access modifier is specified, it defaults to public).

In most scenarios, we do not extend a component class, hence an access modifier is usually unnecessary in my opinion.

There are instances where component inheritance is required. You can read more about it here. Even in such cases, the necessity of an access modifier is debatable.

...

export class MyComponent {
  // service injected as private
  constructor(private _randomSvc: RandomService) {} 

  getRandomNumbers(){ } // keep it public

  @Input()
  myInput: string; // keep it public

  @Output()
  myOutput; // keep it public
}

It's important to note that Javascript itself does not have access modifiers. The use of access modifiers is primarily for development purposes (IDE). While they can be useful in certain situations, I recommend using them sparingly.

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

Expanding on the http class to utilize custom properties within Angular2 typescript

I have developed a CustomHttp class that extends Http similar to the example provided here: To integrate this CustomHttp class, I included providers in the bootstrap function as shown below: bootstrap([ HTTP_PROVIDERS, { provide:Http, use ...

Encountered an error with Aurelia webpack 4 when trying to load a necessary CSS file during runtime

I encountered a unique issue with webpack and aurelia that I can't seem to figure out. After creating a new webpack configuration based on online resources and official documentation, the compilation goes smoothly without any errors. However, during r ...

Icon positioned to the left within the text box

Hey there! I'm new to NativeScript and I've been struggling to place an icon inside a textbox. Can someone please help me out? Expected Output: https://i.stack.imgur.com/xvoZG.png Code <GridLayout columns="*, *" rows=& ...

Firebase: The getIdToken() function returned an error indicating that the promise type is not compatible with a string parameter

When attempting to send the Authorized IdToken as a string in HTTP requests to Firebase, I encountered this error message: Argument of type 'Promise' is not assignable to parameter of type 'string' Firebase Auth: getIdToken() fetc ...

The object assigned in the Facebook login method cannot be utilized

I'm working on integrating Facebook login with Angular 2. Here's the button for logging in: <button ion-button (click)="fbLogin()"><ion-icon name="logo-facebook"></ion-icon>Login using Facebook</button> Below is the clic ...

The entry for "./standalone" in the "@firebase/database-compat" package does not have any documented conditions

Upon running npm run build for my sveltekit project, I encountered the following error generated by vite: 7:55:49 PM [vite-plugin-svelte] When trying to import svelte components from a package, an error occurred due to missing `package.json` files. Contact ...

What is the process for bringing my API function into a different Typescript file?

I've successfully created a function that fetches data from my API. However, when I attempt to import this function into another file, it doesn't seem to work. It's likely related to TypeScript types, but I'm struggling to find a soluti ...

Utilizing React with Typescript to access specific props

I am a newcomer to React and TypeScript and I am facing a challenge while trying to enhance an existing component by creating a wrapper around it. The issue I am encountering is related to adding my custom values to the properties. My goal is to extend th ...

Is it possible for prettier to substitute var with let?

One of the tools I utilize to automatically format my Typescript code is prettier. My goal is to find out if there is a way to have prettier replace all instances of 'var' with 'let' during the formatting process. Below is the script I ...

Retrieve the current user in Spring/Angular and associate the post with the corresponding user profile

Hey there! I've got one more question for you. I am currently working with Spring Security and Angular on the front end. My question is, after logging in, how can I save a post to the current user? Post model: @Id @GeneratedValue private Long id; ...

Encountering a 404 error when utilizing ngx-monaco-editor within an Angular application

I have been encountering an issue while attempting to utilize the editor within my Angular 8 application. Despite researching similar errors on Stack Overflow and GitHub discussions, I haven't found a solution yet. Here's how my angular.json asse ...

When working with Angular Universal, using d3.select may result in a "reference error: document is not defined" in the server.js file

I'm currently working on an Angular project that uses server-side rendering to generate D3 charts. Each chart is encapsulated within its own component, such as a line-chart component which consists of TypeScript, spec.ts, HTML, and CSS files for rende ...

Trouble retrieving key value in HTML with Angular and Firebase

When trying to access the key of an object in my database to navigate to a URL based on it, I am finding that the p.$key value is always undefined. service: getAll(){ return this.db.list('/products').valueChanges(); } component: product ...

Unable to display complete content of Ionic 3 webpage

Trying to print a specific part of an Ionic page which contains a long list of items. However, encountering an issue where the entire list doesn't fit on one page and requires scrolling down to view all items. Expecting the print dialog, triggered by ...

Discovering the interface type of class properties in order to implement a factory method

I am struggling with implementing a factory method in my code. I want to be able to pass not only a Class type to instantiate but also a set of default values for the properties within the class. My goal is to have the compiler notify me if I try to pass i ...

Navigating with query parameters in Angular 5

Currently, I am developing my angular 5+ application and utilizing the AuthGuardService. My scenario involves redirecting from another php application that sends form data through a query string. http://localhost:44200/#/users/save?first_name=John&las ...

The function does not throw a compiler error when a parameter is missing

Currently utilizing TSC Version 2.4.2 Please take note of the following interface: interface CallbackWithNameParameter { cb: (name: string) => void } This code snippet: const aCallback: CallbackWithNameParameter = { cb: () => {} }; Manages t ...

Having trouble with the service connection in Stackblitz?

Objective: I am trying to establish a connection with the Data service in StackBlitz. Issue: Unfortunately, my attempts are not successful. Can anyone pinpoint what I am overlooking? Project Link: https://stackblitz.com/edit/angular-mpy6pr Many th ...

Utilizing req.session in an Express application with Angular (written in TypeScript) when deploying the backend and frontend separately on Heroku

I'm currently facing an issue where I am unable to access req.session from my Express app in Angular. Both the backend and frontend are deployed separately on Heroku. I have already configured CORS to handle HTTP requests from Angular to my Express ap ...

The type 'Data' is lacking the following attributes from its definition

Being a newcomer to Angular 8, I can't figure out why this error is popping up. If you have any suggestions on how to improve the code below, please feel free to share your tips. The error message reads: Type 'Data' is missing the follo ...