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.