I have a several variables on the html of the component which are given their values by the typescript file. It is declared in html as follows:
<h1>{{myproperty1}}<\h1>
<h1>{{myproperty2}}<\h1>
<h1>{{myproperty3}}<\h1>
In the typescript file they are declared in the global scope as follows:
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;
}
Now these values can be updated using this
in a function in the ts file. For example if I wanted to set myproperty1
to something I would do it as follows:
})
export class AppComponent implements OnInit {
myproperty1:string;
myproperty2:string;
myproperty3:string;
myfunction(){
this.myproperty1 = "Hello world";
}
setInterval(()=>{myfunction();},2000);
The problem with this approach is that I lose generality. The function becomes valid for only ONE variable. This is displeasing. The problem scales up much more when the code for the function is longer. I need a function where I can pass
in the value by reference
. For example instead of executing the function for each property, I instead pass
in that specific variable.
Now I understand that in javascript and by extension typescript primitive variables are passed by value and I need to pass an object
, however this also does not help. Let's say I create the following object:
let myobject = {
this.property1:"Lorem",
this.property2:"Lorem",
this.property3:"Ipsum",
}
Now when I execute the function, I need to pass in the specific key
other it does not change the string. For this above object I write the following function and call it:
func(obj){
obj.property1 = "Hello world";
}
func(myobject);
Here if I do not declare property1
it does not modify that entry, instead it appends a new key value pair on the dictionary.
Another method I came across here mentioned using the window
to do this as follows:
var a = 1;
inc = function(variableName) {
window[variableName] += 1;
};
inc('a');
alert(a); // 2
However in angular it gives the following error:
Error: src/app/app.component.ts:86:7 - error TS2322: Type 'string' is not assignable to type 'Window'.
What I want is really just a method of passing in a value by reference which can then be rendered on the html correctly.