Is it recommended to keep Angular properties private and only access them through methods?

I'm starting to get a bit confused with Angular/Typescripting. I originally believed that properties should be kept private to prevent external alteration of their values.

Take this example:

export class Foo{
  private _bar: string;

  constructor(private bar: string){
    this._bar = bar;
  }

  public get bindBar(): string {
      return this._bar;
  }
}

And here is some template code:

<span>{{ bindBar }}</span>

However, I have come across information suggesting performance issues when binding to a method in the HTML template, as methods are called on every change detection event on the page.

The options I am considering are either making it a public property or using Pipes.

Pipes seem like a lot of extra work to implement for every property needing binding, and declaring public variables has typically been discouraged.

I haven't found clear guidance on how to implement binding without impacting performance negatively on the Angular website. Using pipes doesn't seem like the best solution either.

Can someone provide clarification?


Thank you to those who shared links to other articles. From them, I discovered an example illustrating method calls being triggered, so I decided to test whether it was component-based or contained within a single component.

In my modified example, it became evident that the events triggering affected multiple components, not just one. Check out My Stackblitz 2 component test

Answer №1

This particular getter

  public get bindBar(): string {
      return this._bar;
  }

will not impact the performance of your application negatively. Using this getter is just as efficient as directly accessing the variable. During every change detection, all variables in your template are referenced to check for any changes. Therefore, utilizing this getter in your template is no different than referencing a public variable.

If you wish to make a variable read-only, you can simply use the readonly keyword.

readonly bar: string;

Still skeptical? Take a look at this test:

https://stackblitz.com/edit/angular-ivy-zgjwnw?file=src/app/app.component.ts

After running over one million change detection cycles, both approaches take approximately 650 milliseconds with my hardware.


You only need to be cautious about calling methods during change detection if those methods consume significant time or involve API requests. Avoid placing such method calls in your template unless they are triggered by an event.

If performance is your concern, focus on reducing the frequency of change detection triggers and minimizing the number of components checked each time. The default change detection strategy evaluates every single variable and method call in all current component templates upon actions that could potentially cause changes.

The OnPush change detection strategy allows you to specify when component templates should be checked, while the ChangeDetectorRef.detach() service method enables complete detachment of automatic checking for a component.

To delve deeper into this topic, check out this informative article:


I highly recommend setting a breakpoint before invoking

ChangeDetectorRef.detectChanges()
and tracing through a change detection cycle in a debugger. You will observe that the change detector caches the last value of any interpolated values in the template (whether they stem from a property or a method call) within an object called lView (last view). During a change detection cycle, it recalculates these interpolated values - whether via variable reference or method invocation. If there are discrepancies in values, the change detector will update the associated HTML node's content.

In the context of pipes, the change detector scrutinizes the input value and initiates the pipe only if there has been a change in that value. This is due to pipes being considered pure functions (output purely depends on input). Hence, for time-intensive pure methods, transforming them into pipes proves more effective. For instance, scenarios involving string formatting, validation operations, mathematical computations, thorough comparisons, etc.

Answer №2

When working with typescript, utilizing public variables and directly accessing them is generally considered safe. However, issues can arise when using methods during binding, so it is advisable to stick to using variables for your bindings.

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

Convert JSON data into an array of strings that are related to each other

I'm encountering an issue with converting JSON into a string array I must convert a JSON into a string array to dynamically INSERT it into our database, as I need this to work for any type of JSON without prior knowledge of its structure. Here is th ...

What is the best way to wait for the state to be set before mapping the array

I have some data stored in an array (shown in the screenshot below) that I am trying to map, but I am facing issues accessing it as it is loaded asynchronously. How can I await the data? Is there a way to achieve this within the render function? render() ...

Angular AutoComplete feature does not accurately filter the list items

I need to implement an auto-complete feature for the county field due to a large number of items in the list causing inconvenience to users who have to scroll extensively. Currently, there are two issues with the code. The first problem is that although t ...

Showing Firebase messages in a NativeScript ListView in an asynchronous manner

I am currently struggling to display asynchronous messages in a ListView using data fetched from Firebase through the popular NativeScript Plugin. While I have successfully initialized, logged in, and received the messages, I'm facing challenges in ge ...

Error occurred in child process while processing the request in TypeScript: Debug Failure encountered

I encountered the following error in TypeScript while running nwb serve-react-demo: Child process failed to handle the request: Error: Debug Failure. Expression is not true. at resolveNamesWithLocalCache (D:\Projects\react-techpulse-components& ...

Extending Angular 2 functionality from a parent component

As a continuation of the discussion on Angular2 and class inheritance support here on SO, I have a question: Check out my plunckr example: http://plnkr.co/edit/ihdAJuUcyOj5Ze93BwIQ?p=preview Here is what I am attempting to achieve: I want to implement s ...

"Mastering the art of debouncing in Angular using

I am facing an issue where, during a slow internet connection, users can press the save button multiple times resulting in saving multiple sets of data. This problem doesn't occur when working locally, but it does happen on our staging environment. E ...

Implementing asynchronous validation in Angular 2

Recently started working with Angular 2 and encountered an issue while trying to validate an email address from the server This is the form structure I have implemented: this.userform = this._formbuilder.group({ email: ['', [Validators.requir ...

Angular uploading image via WCF service call

I have been facing an issue while trying to upload an image from my Angular frontend through wcf. The upload process is successful and I receive a success message, however, the saved image is not viewable in any image viewer or program. The code snippet u ...

Implement a delay for a specific function and try again if the delay expires

In my TypeScript code, I am utilizing two fetch calls - one to retrieve an access token and the other to make the actual API call. I am looking to implement a 1-second timeout for the second API call. In the event of a timeout, a retry should be attempted ...

Tips for triggering useEffect just once when various dependencies are updated simultaneously

Currently, I have implemented a useEffect hook with two dependencies in the following way: useEffect(() => { ..... }, [apiData, currentMeasurements]); It's important to note that the apiData is fetched using useLazyQuery from apollo/client. Upon ...

Fetching JSON data using Promise.all results in an empty response

I'm facing an issue in my code where I am trying to fetch data from two different JSON files and then return them as arrays. Even after implementing the solution below, it doesn't seem to be working as expected. Can someone guide me on how I can ...

utilizing props to create a navigational link

How can I display a tsx component on a new tab and pass props into the new page? Essentially, I'm looking for the equivalent of this Flutter code: Navigator.push( context, MaterialPageRoute(builder: (context) => Page({title: example, desc: ...

Using Angular 2 to assign unique ids to checkbox values

Is there a way to retrieve the value of a checkbox in Angular 2 without needing an additional Boolean variable? I am trying to toggle the enabled/disabled state of an input field based on the selection of a checkbox. While I know this can be accomplished ...

Ways to generate an array containing the headings from a list using typescript?

How can I extract the headers of objects in an array in TypeScript? let data = [{name: "A", skills: 50, result: 80}, {name: "B", skills: 40, result: 90}, {name: "C", skills: 60, result: 60}]; let headers = Ob ...

Displaying Information in Angular Modal Windows

I'm facing an issue while trying to create an edit button for a formGroup that is initially saved. When the user clicks on the adjacent button, a modal should open with editable data. However, I encountered this error and haven't been able to res ...

Sharing information between Angular components

Having recently started using Angular, I'm facing an issue with passing an array to a different component that is not parent or child related. What I aim to achieve is: upon selecting rows from the first component table, a new view should open up disp ...

The mat-select component in Angular Material is failing to update/refresh when a new value is

Attempting to design an Angular Form for editing a record. When the user navigates to this edit form from the records list page, I aim to populate the fetched record from the API into the form elements while it loads. Utilizing the patchValue method within ...

The optimal and most secure location for storing and retrieving user access credentials

After receiving a list of locations accessible to the session user from the server, I am seeking the ideal location to store these roles in Angular. This will allow me to determine whether or not to display specific routes or buttons for the user. Where ...

Can we modify the auto-import format from `~/directory/file` to `@/directory/file`?

I have a small issue that's been bugging me. I'm working on a project using Nuxt3 and Vscode. When something is auto-imported, Vscode uses the ~/directory/file prefix instead of the preferred @/directory/file. Is there an easy way to configure Vs ...