'Angular 4 with TypeScript: passing parameters by reference
I'm just starting to develop a web application with angular 4 with TypeScript language. My question is: if I initialize a string variable with the value of a data field in my class, it looks like the value is passed for copy and not for reference.
Is there a way to pass the parameter for reference?
Example:
export class MyObject {
string1: string;
string2: string;
}
export class MyClass {
myString: string;
object: MyObject;
array[]: MyObject[];
constructor() {
this.array = [{
string1: this.myString;
string2: this.myString;
}];
}
}
If I tried to change the value of field this.myString and then use string interpolation in my HTML template
{{myString}}
{{array[0].string1}} {{array[0].string2}}
the only value that has changed is myString, while the other two values remained the same as myString's first value. This is because it seems that the passage of the parameters has been done for value and not by reference.
Sorry if the question is trivial, but I'm learning TypeScript right now
Solution 1:[1]
You should to change value from array like
<input [(ngModel)]="array[0].string1">
In ur array new instances of myString;
Solution 2:[2]
This is generally the way variables work in Javascript (also most other modern programming languages, Java, C#, etc). A common way to pass by reference is to create an additional object that holds the string and assign the reference to that object anywhere you need it.
For example:
export interface MyObject {
string1: Ref;
string2: Ref;
}
export interface Ref {
value: string
}
export class MyClass {
myString: Ref;
array: MyObject[];
constructor() {
this.myString = { value: "old Vlaue"};
this.array = [{
string1: this.myString,
string2: this.myString
}];
this.myString.value = "New Value"
}
}
When you bind you then use:
{{myString.value}}
{{array[0].string1.value}} {{array[0].string2.value}}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alex Kvitchastiy |
| Solution 2 | Hamlett |
