我在组件的 html 上有几个变量,它们由打字稿文件赋予它们的值。它在html中声明如下:
<h1>{{myproperty1}}<\h1>
<h1>{{myproperty2}}<\h1>
<h1>{{myproperty3}}<\h1>
在打字稿文件中,它们在全局范围内声明如下:
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;
}
现在可以在 ts 文件的函数中使用 this
更新这些值。例如,如果我想将 myproperty1
设置为某些东西,我会这样做:
})
export class AppComponent implements OnInit {
myproperty1:string;
myproperty2:string;
myproperty3:string;
myfunction(){
this.myproperty1 = "Hello world";
}
setInterval(()=>{myfunction();},2000);
这种方法的问题是我失去了一般性。该函数仅对一个变量有效。这令人不快。当函数的代码更长时,问题会扩大得多。我需要一个函数,我可以通过 pass
在值中 reference
。例如,我没有为每个属性执行函数,而是在该特定变量中pass
。
现在我明白在 javascript 和扩展中,typescript 原始变量是按值传递的,我需要传递一个 object
,但这也无济于事。假设我创建了以下对象:
let myobject = {
this.property1:"Lorem",
this.property2:"Lorem",
this.property3:"Ipsum",
}
现在,当我执行该函数时,我需要传入 specific key
其他它不会更改字符串。对于上面这个对象,我编写了以下函数并调用它:
func(obj){
obj.property1 = "Hello world";
}
func(myobject);
在这里,如果我不声明 property1
,它不会修改该条目,而是在字典上附加一个新的键值对。
我遇到的另一种方法 here 提到使用 window
执行此操作,如下所示:
var a = 1;
inc = function(variableName) {
window[variableName] += 1;
};
inc('a');
alert(a); // 2
但是在 angular 它给出了以下错误:
Error: src/app/app.component.ts:86:7 - error TS2322: Type 'string' is not assignable to type 'Window'.
我想要的实际上只是一种通过引用传递值的方法,然后可以将其正确呈现在 html 上。
答案 0 :(得分:-1)
您可以选择声明属于相应组件的属性(或您希望有效的属性)类型的参数。
然后就可以使用索引类型来访问属性了。
像这样:
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!';
}
}
编辑:
例子:
https://stackblitz.com/edit/angular-nhjsec?file=src/app/app.component.html
答案 1 :(得分:-1)
执行此操作的方法是使用一个对象并将该对象用于 html 页面上的值的插值。现在假设您要更新 html 上的一些值。您按如下方式分配它们:
app.component.html
<h1>{{object.property1}}<\h1>
<h1>{{object.property2}}<\h1>
<h1>{{object.property3}}<\h1>
现在在 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'
}
}
现在以这种方式声明它们的重点是不失一般性。通过这种方式,您无需为每个属性创建单独的函数,而是通过引用访问该属性中的 pass
,并且它的更改值也会在 html 页面上更新。
为了阐述我的观点,假设我编写了一个函数,它将接受一个字符串并将特定属性设置为这个新值,并且我们希望能够使用相同每个属性的函数。我们按如下方式使用此对象:
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);
}
结果:我们已经成功地将函数推广到任何给定的属性,而无需对任何值进行硬编码。