Creating dynamic class fields when ngOnInit() is called in Angular

I am trying to dynamically create variables in a class to store values and use them in ngModel and other places. I understand that I can assign values to variables in the ngOnInit() function like this:

export class Component implements OnInit{
   name: string;
   ngOnInit(){
       this.name = 'John Doe';
   }
}

However, I am encountering an issue - I retrieve my fields from a server API and do not know what or how many items I will get. I can only parse the server response and assign values to new variables after receiving them.

I cannot do it like this (TS2540: Cannot assign to 'name' because it is a constant or a read-only property.)

export class Component implements OnInit{
   ngOnInit(){
       name = 'John Doe';
   }
}

How can I assign new fields to my class in ngOnInit() or perhaps in another place? (I believe I can do it in the constructor, but the documentation advises against using it with Observable calls to APIs and other complex operations)

Answer №2

To avoid compiler errors when using non-existing property names, you can implement an indexer in your class:

export class Component {
    [name: string]: any;
    ngOnInit(){
        this["name"] = 'John Doe';
        this.nameaa = "dd"
    }
}

However, be cautious as this approach allows for the possibility of misspelling property names without triggering any compilation errors.

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

Accessing data outside of the scope when looping through items in Angular forEach

I am currently working on retrieving the Game ID generated by the APIService.postData method for the game. The goal is to utilize this Game ID within the Angular foreach loops to maintain foreign key constraints on the RESTful side. Any advice on extracti ...

Effectively controlling two distinct Azure resources within one domain name through domain routing

I am currently in the process of deploying a React application on Microsoft Azure that includes a basic content management feature. Essentially, when users visit the website and access static content, the app retrieves HTML code from a database and display ...

What is the best way to specify types for a collection of objects that all inherit from a common class?

I am new to typescript and may be asking a beginner question. In my scenario, I have an array containing objects that all extend the same class. Here is an example: class Body{ // implementation } class Rectangle extends Body{ // implementation } class ...

What are the steps for generating website endpoints using search query outcomes?

I am currently working on a ReactJS website as a part of my web development bootcamp project. One interesting feature I have incorporated is a search functionality that uses Flask routes to connect ReactJS endpoints (../Language.js) with my Sqlite3 databa ...

At what point does Math.random() begin to cycle through its values?

After running this simple test in nodejs overnight, I found that Math.random() did not repeat. While I understand that the values will eventually repeat at some point, is there a predictable timeframe for when it's likely to happen? let v = {}; for ( ...

Encountering an 'undefined' response when passing an array in Express's res.render method

After my initial attempt at creating a basic node app, I discovered that the scraper module was working correctly as data was successfully printed in the command window. Additionally, by setting eventsArray in index.js, I confirmed that Express and Jade te ...

In the realm of JavaScript, "this" is a key player when referring to an object within a factory

I created some JavaScript classes and FunctionFactories for them, but I believe there are errors in my implementation. To make the code more understandable, I decided to rename certain parts of it. The main class is called the "root"-class, which has chi ...

Refresh the current page with jQuery Mobile when it is clicked

I have a multi page template in jQuery Mobile. How can I refresh the current page when clicking on a hyperlink or button? I am using JQM version 1.4.5 Despite trying the code suggested in how to refresh(reload) page when click button in jQuery Mobile, it ...

"Error: imports are undefined" in the template for HTML5 boilerplate

After setting up an HTML5 Boilerplate project in WebStorm, I navigate to the localhost:8080/myproject/src URL to run it. Within the src folder, there is a js directory structured like this: libraries models place.model.ts place.model.js addr ...

Make a call to a remote node.js server using an ajax request

My setup involved a basic nodejs server (including CORS) : var express = require('express'); var app = express(); var http = require('http').Server(app); var io = require('socket.io')(http); var port = 8001; http.listen(port, ...

The table refuses to load

I've been troubleshooting this issue for the past two days. The array is visible in the console, but it refuses to show up on the table. I've tried multiple approaches, but none seem to work. I suspect that "tobodyHtml" is not defined properly, a ...

typescript import { node } from types

Exploring the possibilities with an electron application developed in typescript. The main focus is on finding the appropriate approach for importing an external module. Here is my typescript configuration: { "compilerOptions": { "target": "es6", ...

Tips on how to customize/ng-class within a directive containing a template using replace: true functionality

To keep replace: true, how can ng-class be implemented on the directive below without causing conflicts with the template's ng-class? This currently results in an Angular error: Error: Syntax Error: Token '{' is an unexpected token at co ...

The filter becomes ineffective once I remove the input value

Check out this HTML table containing an input field that filters plans. https://i.stack.imgur.com/UfIw2.png I input the value => 1 The filter successfully works https://i.stack.imgur.com/CsQXh.png Removing the value (1) displays all recordings, totali ...

Tips for adjusting the size of icons in Ionic Framework v4 and Angular 7

The library ngx-skycons offers a variety of icons for use in projects. If you're interested, check out the demo here. I'm currently incorporating this icon library into an Ionic project that utilizes Angular. While the icons work perfectly, I&ap ...

Incorporating Microsoft's Emotion API into an HTML website

Currently, I am attempting to develop a HTML webpage that can detect emotions from images submitted by the user. By referring to Microsoft's documentation, I have produced the following HTML file: <!DOCTYPE html> <html> <head> & ...

Executing the slideToggle() function in JQuery with javascript

Trying to create a script that expands and collapses when users click on either the text or image. The image is a basic arrow that switches to an arrow pointing upwards when the div is expanded. The issue I'm facing is that the text disappears when t ...

Struggling with TypeScript Errors while Extending Theme Colors in Material UI React using TypeScript

Just started with typescript and feeling a bit lost, can someone offer some guidance? I'm working on a React project using material-ui with typescript. To add a new color the correct way, it needs to be added to a theme: const theme = createMuiTheme({ ...

Error occurs in React Native when trying to import routes due to type mismatch

My react native app is running on my physical device, but I encountered an error when importing routesContainer in my app.js. Can anyone shed some light on why this error is occurring? TypeError: Super expression must either be null or a function [Mon Oct ...

Removing all HTML elements within the div container

My HTML code includes the following: <div class="row" id="conditional-one"> <div class="large-12 columns"> <h3><?php echo $arrayStage_rule_one_title?></h3> <p> <?php echo $arrayS ...