简体   繁体   English

在 typescript [Angular 8] 中通过引用传递变量

[英]Passing variables by reference in typescript [Angular 8]

I have a several variables on the html of the component which are given their values by the typescript file.我在组件的 html 上有几个变量,它们的值由 typescript 文件给出。 It is declared in html as follows:在 html 中声明如下:

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

In the typescript file they are declared in the global scope as follows:在 typescript 文件中,它们在全局 scope 中声明如下:

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.现在可以在 ts 文件中的 function 中使用this来更新这些值。 For example if I wanted to set myproperty1 to something I would do it as follows:例如,如果我想将myproperty1设置为某事,我会这样做:

 
})
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. function 仅对 ONE 变量有效。 This is displeasing.这是令人不快的。 The problem scales up much more when the code for the function is longer.当 function 的代码更长时,问题会更加严重。 I need a function where I can pass in the value by reference .我需要一个 function ,我可以在其中通过reference pass值。 For example instead of executing the function for each property, I instead pass in that specific variable.例如,我没有为每个属性执行 function,而是pass该特定变量。

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.现在我明白在 javascript 和扩展 typescript 原始变量是按值传递的,我需要传递一个object ,但这也无济于事。 Let's say I create the following object:假设我创建了以下 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.现在,当我执行 function 时,我需要传入specific key ,否则它不会更改字符串。 For this above object I write the following function and call it:对于上面的 object 我写了以下 function 并调用它:

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.在这里,如果我不声明property1它不会修改该条目,而是在字典上附加一个新的键值对。

Another method I came across here mentioned using the window to do this as follows:我在这里遇到的另一种方法提到了使用window来执行此操作,如下所示:

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

inc('a');

alert(a); // 2

However in angular it gives the following error:但是在 angular 中,它给出了以下错误:

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.我想要的实际上只是一种通过引用传递值的方法,然后可以在 html 上正确呈现。

You have the option to declare a parameter that is of type of the properties of the respective component (or the properties you want to be valid).您可以选择声明一个参数,该参数属于相应组件的属性(或您希望有效的属性)的类型。

Then you can use the index type to access the property.然后您可以使用索引类型来访问该属性。

Something like this:像这样的东西:

type props = 'prop1' | 'prop2';

export class MyComponent {
  prop1: string = '';
  prop2: string = '';
  prop3: number = 0;  // can't be passed to updateProp because not assigned to type props

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

EDIT:编辑:
Example: https://stackblitz.com/edit/angular-nhjsec?file=src/app/app.component.html示例: https://stackblitz.com/edit/angular-nhjsec?file=src/app/app.component.html

The way to go about doing this is by using an object and using that object for the interpolation of the value on the html page. go 关于这样做的方法是使用 object 并使用 object 对 ZFC35FDC70D5FC69DE3 页面上的值进行插值。 Now say you want to update some values on the html.现在假设您要更新 html 上的一些值。 You assign them as follows:您按如下方式分配它们:

app.component.html app.component.html

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

Now in the ts file we declare them as follows:现在在 ts 文件中我们声明它们如下:

app.component.ts 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'
        }

}

Now the whole point of declaring them in this way to not lose generality.现在以这种方式声明它们的重点是不失一般性。 In this way instead of creating a separate function for each property, you get to pass in that property by reference and it's changed value is also updated on the html page.通过这种方式,您无需为每个属性创建单独的 function,而是通过引用pass该属性,并且它的更改值也会在 html 页面上更新。 In order to elaborate my point, say I write one function which will take a string and set a specific property to this new value and we want to be able to use the same function for each property.为了阐述我的观点,假设我写了一个 function 它将接受一个字符串并将特定属性设置为这个新值,我们希望能够为每个属性使用相同的 function。 We do so using this object as follows:我们使用此 object 执行此操作,如下所示:

app.component.ts 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 : We have successfully generalized the function to be used for any given property without having to hardcode any values.结果:我们已成功推广 function 以用于任何给定属性,而无需对任何值进行硬编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM