Issue with Readonly modifier not functioning as expected in Angular/Typescript

My goal is to create a component property that is read-only. However, I am facing an issue where the readonly modifier does not seem to have any effect.

View example on stackblitz

According to the documentation, once I initialize the cars property in the constructor() of AppComponent, it should not be modifiable.

What I have attempted:

Initially, I was able to modify the cars property in AppComponent's ngOnInit(). I assumed this might be allowed as the component is still under construction. To test further, I created a button that calls a function to modify the property and found that I could do so again. This led me to think that maybe the readonly modifier only applies when accessed by external classes. However, even in HelloComponent, I could still modify cars.

Am I misunderstanding how readonly works? How can I correctly implement it to make a property accessible publicly but non-modifiable (read-only) from outside sources?

Answer №1

Immutable The keyword "readonly" is used in interfaces or classes to designate a property as immutable.

class Employee {
    readonly empCode: number;
    empName: string;

    constructor(code: number, name: string)     {
        this.empCode = code;
        this.empName = name;
    }
}
let emp = new Employee(10, "John");
emp.empCode = 20; //Compiler Error
emp.empName = 'Bill'; //Compiler Error

It's important to note that an immutable property can only be assigned a value in the constructor or when initially declaring the property.

An immutable property cannot be reassigned once it has been set.

In the provided code example:

 modifyCars() {
    this.cars[0] = { id: -1, name: 'MODIFIED BY BUTTON' };
  }

Instead of reassigning values, you are mutating the array. To prevent array mutation, you can use the ReadOnly mapped type.

Replace

  readonly cars;

with

readonly cars: Readonly<{ id: number, name: string }[]>;

See full example here

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

You are unable to elongate the interface 'http.IncomingMessage'. Were you intending to use 'implements' instead?

I have been struggling to execute the serve command for my angular project, encountering errors every time. Despite searching on Google for solutions, I have now reached a point where none of the answers seems to be helping. I recently downloaded a MEAN st ...

How to Utilize Output() and EventEmitter() for Value Transmission in Angular Application

Last week I was successfully able to implement Output() and EventEmitter() in my Angular app. However, today I am facing a new challenge while trying to apply the same concept in a different scenario. I'm not sure what I might be overlooking. Firstly ...

When you eliminate the Angular root element, what are the consequences that follow?

I am in the process of manually bootstrapping an Angular application. ngDoBootstrap(app) { app.bootstrap(AppComponent); } Each time the root element is removed from the DOM and re-injected, I bootstrap the application again. This cycle repeats multip ...

Issue with CSRF token validation in ASP.NET Core when integrating with Angular

To enhance the security of my application, I decided to implement CSRF-Token protection using Angular documentation as a guide. According to the Angular docs, if a cookie named XSRF-TOKEN is present in the Cookies, it will automatically be included in the ...

What is the method to acquire the firestore reference type in TypeScript?

Here is the code I am working with: import { DocumentReference } from '@firebase/firestore-types' export type Recipe = { author: string title: string ingredients: { quantity: number ingredient: DocumentReference["path"] ...

ReactJS tweet screenshot capture

Currently seeking a solution to capture a tweet screenshot, store it in a PostgreSQL database, and display it on my ReactJS webpage using Typescript. I have been utilizing react-tweet-embed for displaying the tweet, but now I require a method to save the i ...

Error TS2322: Type 'Partial<T>' is not assignable to type 'T'

I'm struggling to articulate my problem, so I think the best way to convey it is through a minimal example. Take a look below: type Result = { prop1: { val1: number, val2: string }, prop2: { val1: number } }; f ...

Experiencing issues with Errors when Targeting ES5 in Angular2 TypeScript?

In my development environment, the npm version is 3.10.10, and I want to create a new Angular2 project from scratch. When I try running npm install angular2 --save I encounter this error message: Error Image After referring to this answer which recomm ...

Discover the seamless transformation of a class definition into a Vue 3 component definition utilizing the dazzling 'tc39' decorators

The proposed API in the tc39/proposal-decorators repository is significantly different from the previous decorators API. Although TypeScript 5 doesn't fully support the new API yet, it's only a matter of time before the old API becomes deprecated ...

The concept of Material Design: Utilizing a grid system with automatic card height

Is there a way to create a grid with cards that have auto height, similar to this example: https://i.sstatic.net/2y87g.png I am currently using Material Design and Angular 4, but I am also open to solutions involving React or VueJS. I have tried using th ...

Issue: Incompatibility in metadata versions detected for module .../ngx-masonry/ngx-masonry.d.ts. Level 4 version identified, whereas level 3 version

When using ngx-masonry, I encountered the following error message- ERROR in Error: Metadata version mismatch for module .../ngx-masonry/ngx-masonry.d.ts, found version 4, expected 3 Specifications: Angular 4 ngx-masonry 1.1.4 ...

Exploring Objects within an array using Angular loops

Hey there, I'm currently working on an Angular project and I need to retrieve the userName of the user for each comment that is posted. These entities are coming from my Spring Boot project. Is there a way to access the username for every comment? He ...

Utilize *ngFor in Angular 9 to showcase both the key and values of an array

JSON Data { "cars": { "12345": [1960, 1961, 1962], "4567": [2001, 2002] } } HTML Template <strong>Plate and Year</strong> <div *ngFor="let car of cars"> {{car}} </div> This should be di ...

Unable to retrieve values from nested objects in component.html

Hey fellow tech enthusiasts, I'm currently dealing with a complex nested JSON object retrieved from an API. Here's a snippet of the object: profile : { title:"Mr", personalInfo:{ fullNames: "John Doe", id ...

Retrieve the specified data stored within the ngValue attribute of an Angular 4 component

I am currently working on an Angular 4 project and I have a requirement to extract the value of the selected option from a dropdown menu in my component. Specifically, I am trying to retrieve the value of policyType.id, which is stored in the [ngValue] att ...

The system encountered difficulty handling a recursive structure

I am facing a challenge with a recursive JSON structure that needs to be stored as a series of maps with keys. The structure comprises flows and subflows that have references to each other. Here are the type declarations, noting that the issue lies in the ...

Utilize the Lifecycle Interface within Angular 2 framework for enhanced application development

Can you explain the impact of this rule? "use-lifecycle-interface": true, ...

TestCafe Environment Variables are not properly defined and displaying as undefined

Exploring TestCafe and diving into the world of automated testing. Trying to master the tools with guidance from Successfully executing code on my Windows setup! fixture`Getting Started`.page`http://devexpress.github.io/testcafe/example`; test("My ...

Incorporating a JavaScript script into my Angular 7 project

My project requires me to incorporate the "Loadingbar.js" library into one of my pages. You can find this library here: . Initially, I inserted the CSS code into my global "style.css" file. I started by placing the script in my index.html file: <script ...

Roll out a custom-built server for an Angular 7, MongoDB, Express, and Node application

I am seeking to host my Angular application with Node.js, MongoDB, and Express.js on a server of my own. My current deployment method involves: -> ng build --prod (generates output in the dist folder) -> ng serve from the dist directory To start th ...