Using references to pass variables in TypeScript [Angular 8]

I have several variables within the html of this component that are assigned their values by the typescript file. The declaration in the html is as follows:

<h1>{{myproperty1}}<\h1>
<h1>{{myproperty2}}<\h1>
<h1>{{myproperty3}}<\h1>

In the typescript file, these variables are declared in the global scope like so:

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
 
})
export class AppComponent implements OnInit {
  myproperty1:string;
  myproperty2:string;
  myproperty3:string;
}

These values can be updated using this within a function in the typescript file. For example, to set myproperty1 to a specific value:

 
export class AppComponent implements OnInit {
       myproperty1:string;
       myproperty2:string;
       myproperty3:string;

myfunction(){
       this.myproperty1 = "Hello world";
}

setInterval(()=>{myfunction();},2000);

The issue with this approach is that it lacks generality. The function only applies to one variable, which is not ideal, especially for longer code. I need a way to pass in the value by reference instead.

While I understand that primitive variables in javascript and typescript are passed by value, passing an object doesn't fully solve the problem. Even when creating an object like:

let myobject = {
        this.property1:"Lorem",
        this.property2:"Lorem",
        this.property3:"Ipsum",
}

Executing the function requires specifying the specific key for the change to take effect. Another method referenced here, involves using the window:

var a = 1;
inc = function(variableName) {
  window[variableName] += 1;
};

inc('a');

alert(a); // 2

This method triggers an error in Angular related to type assignment. What I truly desire is a way to pass in a value by reference that reflects correctly in the rendered html.

Answer №1

To accomplish this task, utilize an object for interpolating values on the HTML page. Suppose you need to update specific values on the HTML; assign them as shown below:

app.component.html

<h1>{{object.property1}}<\h1>
<h1>{{object.property2}}<\h1>
<h1>{{object.property3}}<\h1>

In the TypeScript file, declare them like this:

app.component.ts

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
 
})
export class AppComponent implements OnInit {
  object = {
        property1: 'somestring',
        property2: 'somestring',
        property3: 'someotherstring'
        }

}

By structuring it in this manner, you maintain generality. By referencing the object's properties, you can dynamically update their values on the HTML page without creating separate functions for each one.

To illustrate, imagine a single function that updates a specific property with a new value, which we want to use for all properties. By leveraging the object, achieve this as follows:

app.component.ts




export class AppComponent implements OnInit {
  object = {
        property1: 'somestring',
        property2: 'somestring',
        property3: 'someotherstring'
        }
  modifydata(x:string,value:string){
       this.object[value] = x;
        }


    //call the function

  setInterval(()=> {
        var mystring = 'property1';
        this.modifydata('hello world',mystring);},2000);


}

RESULT: The function is now generalized and can be applied to any property without hardcoding specific values.

Answer №2

To declare a parameter as the type of properties within a specific component, or the desired properties, is an available option.

By utilizing the index type, you can then access these properties accordingly.

An illustration of this concept:

type props = 'prop1' | 'prop2';

export class MyComponent {
  prop1: string = '';
  prop2: string = '';
  prop3: number = 0;  // This property cannot be passed to updateProp since it is not part of type props

  updateProp(p: props) {
    this[p] = 'Updated!';
  }
}

EDIT:
For example: https://stackblitz.com/edit/angular-nhjsec?file=src/app/app.component.html

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

Develop an Angular application and deploy it on an IIS server

I've been facing issues while trying to deploy my Angular app on IIS. After researching, I found that using the cli command ng build resulted in errors such as Module not found. Interestingly, when I modified the templateUrl in the component, the erro ...

The function navigator.canShare() encountered a permissions denial while running in Typescript

Currently, I am in the process of developing an Angular8 PWA and have successfully implemented webshare to share text content. To my excitement, Chrome has now extended its support for file sharing starting from May 2019. However, while attempting to int ...

Converting a TypeScript nested dictionary into a list of strings

I am currently working with a nested dictionary and my goal is to convert it into a list of strings. For example, the initial input looks like this: var group = { '5': { '1': { '1': [1, 2, 3], ...

Explain what one-time typescript interfaces are

As someone who has been using React for quite some time, I am now looking to integrate Typescript into my projects. In the past, I would create large "container" objects like this: const theme = { colors: { primary: '#00f', accent: &ap ...

Obtain data from a single module and incorporate it into a different one

In my Angular 2 application, I am dealing with two component files - home.ts and folder-selector.ts. Within the folder-selector.ts file, there is a variable named pathToNode. I am trying to figure out how to access this value from within the home.ts file ...

Using ExpressJS to generate a page with inputs

Using ExpressJS, I have created an Object of the IndexController in my router (index.js) and passed a String as a constructor argument. I then attempted to call the showDefaultFeed method. Expected output from "index.hbs" view was to print the argument pa ...

What is the process for utilizing GruntFile.coffee and package.json to extract or create the Lungo.js example files?

I want to experiment with the Lungo.js examples found here: https://github.com/tapquo/Lungo.js. However, when I try to run the index.html in the example directory, it seems like the components and package directories are empty. Although these directories d ...

What is the most effective way to inform the user when the nodeJS server can be accessed through socketIO?

I have developed a web app that indicates to the user when the server is online for data submission. Although the current code functions properly for single-user interaction, I am facing an issue where one user's connection or disconnection directly i ...

Ways to dynamically refresh a Vue component when data is updated without the need to manually reload the

After fetching data using axios, I noticed that my Vue component doesn't update automatically after a click event or when the data changes. As a workaround, I have to refresh the page to see the updated data. Is there a simple solution to this issue? ...

How can I retrieve a formController in AngularJS?

When trying to reset the data in a form and calling form.setPristine(), I encounter an issue where the formController is not registered within the $scope. It may sound like a basic question, but how can I locate the formController? Within the code snippe ...

Creating a function to limit the display value of Material UI Autocomplete similar to Material UI Multiple Select's renderValue

Incorporating Material UI Features Utilizing the Material UI Multiple Select, you have the ability to truncate the displayed value after selection instead of wrapping onto another line by setting the renderValue to .join for the selected options, enabling ...

Adding the most recent version of jquery causes the webpage to malfunction

Currently, I am facing a challenge on a website that has an outdated version of jQuery (1.7.2) included in the header. In order to use a plugin that requires the latest version of jQuery, I tried linking the newer version (2.1.3) in the footer. However, j ...

Error with setting innerHTML property of a null nested div

This issue arises when the element is referenced before the DOM has completely loaded. To combat this, I have ensured that the necessary script runs only after the window has finished loading. Interestingly, if the getElementById() call is for a standalon ...

Uploading Files with PhoneGap using Ajax

I have been attempting to execute this PhoneGap example for uploading images from a device to a server. // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // functi ...

"The controller seems to always return an 'undefined' value for the Angular

Within my project, I have implemented ui-view with the following structure: <main class="content"> <div class="inner" ng-controller="OrderPageController"> <div ui-view="main-info"></div> <div ui-view="comment ...

I encountered a problem when trying to set up ngx-Spinner version 8.0.3

I need help implementing a spinner loader in my app. I have followed the instructions provided at [ https://www.npmjs.com/package/ngx-spinner ] and successfully installed it. However, when trying to import and add it to "imports", I encountered the follow ...

Sending information from one page to another and then sending it once more

I am currently utilizing the following code to submit a form's data to : <script type="text/javascript"> $(document).ready(function(){ $("#textnextofkin").validate({ debug: false, rules: { ...

No change in the element's text content when clicking

I'm working on creating a timer that counts down from either 15 or 30 seconds. However, I'm having trouble changing the text value when the 15 button is clicked. Can someone help me figure out what's wrong? Thank you in advance HTML <h ...

Exploring the capabilities of Node.js functions

I'm currently exploring Node.js and struggling to understand how functions are created and used. In my code snippet: var abc={ printFirstName:function(){ console.log("My name is abc"); console.log(this===abc); //Returns true ...

Tips for enhancing a JSON array by including attributes through JavaScripts

I need help in dynamically constructing JSON using Javascript. { "Events": [{ "Name": "Code Change", "Enabled": "true", "Properties": [{ "Name": "url", "Value": "val" }] }], "Properti ...