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

"Unlocking the Power of Angular: Mastering the Art of Ch

Within my angular 7 project, I am looking to chain together multiple HTTP Get requests. However, I want each call to wait until the previous one has completed even if I don't require the response directly in the next call. I am trying to avoid nestin ...

Tips for making a oneOf field nullable using TypeScript and AJV

A field named platform exists in my code, and it can hold either a string or an array of strings (string[]). The field can also be nullable or undefined if not passed as input. TypeScript Interface export interface IEntityLeaderboardQuery { rank: stri ...

Is it possible that .focus() does not function on a duplicated object?

Greetings to all! I have created a form with rows of input text fields. Users can add as many rows as needed by clicking the 'add row' button. The functionality to clone() for adding rows is working perfectly. In each row, an input field can o ...

Transmit the Boolean value to the controller using ajax requests in asp.net.core with C# programming

Within the view section, there is a form that includes a checkbox input. <div class="checkbox"> <label class="">active</label> <div class="icheckbox_flat-green checked" style="position: relative;"> <input type="checkbox" id="A ...

jsp fullcalendar select not functioning properly

The code snippet for the select: function within fullcalendar is as follows: select: function(start, end, jsEvent, view) { if (start.isBefore(moment())) { $('#calendar').fullCalendar('unselect'); return false; } else { //ajax Cal ...

Is it possible to extract a string from a file and import the extracted string into another file using require() in NODE.js?

My file structure looks like this: collegesapp ├── node_modules │ ├── express │ ├── connect │ ├── jade │ └── passport ├── routes │ └── routes.js ├── views │ ├── index.jade │ ...

Issue with exclude not functioning in tsconfig.json for Angular Typescript deployment

I am encountering an issue with a module within the node_modules directory while compiling my Angular 4 project. The error messages I'm receiving are as follows, even after attempting to exclude the problematic module in the tsconfig.json file. Can an ...

Troubleshooting: :before element not being hidden by jQuery slidetoggle()

My elements are all behaving correctly with the slidetoggle() function, except for my li:before class. I've attempted to manipulate the overflow, visibility, display, and other properties of both the :before pseudo-element and the li element, but the ...

The function Sync in the cp method of fs.default is not a valid function

When attempting to install TurboRepo, I encountered an issue after selecting npm. >>> TURBOREPO >>> Welcome to Turborepo! Let's get you set up with a new codebase. ? Where would you like to create your turborepo? ./my-turborepo ...

Prioritize returning AJAX data over iterating through the parent loop

Hey everyone, I'm having trouble wrapping my head around this issue even after researching various scenarios online. Here's what's going on: I have an array of strings named recipientsList. What I want to do is make an AJAX call for each s ...

Add a new module to your project without having to rely on the initial

I'm looking to experiment with a module by making some adjustments for testing purposes. You can find the code here. Currently, all I need to do is type "npm install angular2-grid" in my terminal to add it to my project. Here's my concern: If ...

"I am looking for a way to receive a response from a loopback in Angular7

Currently, I am utilizing angular7 with loopback. While I can successfully retrieve data, I am unsure how to receive error messages and response statuses. It would be helpful for me to understand what my response code is at the time of the request. Output ...

Creating a custom directive in Angular 2 that restricts input to text only

I have recently created a directive that specifically allows only numbers by using key codes. However, I've noticed that when I try to copy and paste text into the text box, it accepts the input but does not display it. Is there a way to utilize &apo ...

Is the jQuery AJAX call using POST method being retrieved as $_GET?

Below is a snippet of code that I've successfully implemented: <script type="text/javascript"> $(document).ready(function() { // Initializing the table $('#table_1').tableDnD({ onDrop: function(table, row) { $.tab ...

Experiencing TypeScript error in VSCode while trying to run in Nodejs? Here's how to troubleshoot and resolve

Experimenting with the performance measurement code provided by Nodejs in VSCode has been an interesting challenge for me. I encountered no issues running the code in Nodejs, and it executed smoothly. However, when attempting to run the code in VSCode, er ...

Limit not reached by substring function

When the character limit exceeds 20 characters, the substring function extracts the first 20 characters typed in the input. It replaces any additional characters that are entered after reaching the max limit of 20. In my program, however, I am able to con ...

"Attempt to create angular fork results in an unsuccessful build

I have recently created a fork of angularJs and I am facing an issue when trying to build it. The build process fails when running grunt package npm -v --> 3.5.2 bower --version --> 1.7.2 I followed the steps provided in the official documentation to bu ...

The AngularJS 2 TypeScript application has been permanently relocated

https://i.stack.imgur.com/I3RVr.png Every time I attempt to launch my application, it throws multiple errors: The first error message reads as follows: SyntaxError: class is a reserved identifier in the class thumbnail Here's the snippet of code ...

Capture Video on iOS devices using the MediaRecorder API and display it using HTML5 Video Player

Issue: I am facing an issue where I cannot record video or get a video stream from the camera on iOS through my Angular web application built using ng build. Investigation: In my investigation, I explored various websites that discuss Apple iOS features ...

Incorporating an HTML file into a DIV container while also displaying menu links

I am facing a major challenge with what I recognize as a relatively simple issue for experts. As someone who is still learning, I am struggling to create menu links that load an HTML file into a specific DIV. Despite my efforts, the content keeps loading i ...