![](/img/trans.png)
[英]Angular2 typescript how to get object properties to display in template
[英]Angular2/Typescript object and property binding to template
注意:我想知道正确的方法或更多
_____________________________________________________________________
ANGULAR1
在angular1
,我们可以执行以下操作。
$scope.user={};
$scope.user.name="micronyks";
$scope.user.age="27";
或直接喜欢
$scope.user={name:"micronyks",age:"27"}
绑定到模板的样子,
<div>My name is {{user.name}} & I'm {{user.age}} year(s) old. </div>
______________________________________________________________________
ANGULAR2
在与打字稿 angular2,
models.ts
export class LoginModel()
{
private name:string;
private age:number;
}
app.ts
import {LoginModel} from '../models.ts';
user=new LoginModel()
constructor()
{
this.user.name="micronyks"
this.user.age="27"
}
app.html
<div>My name is {{user.name}} & I'm {{user.age}} year(s) old. </div
<div>My name is {{user.name}} & I'm {{user.age}} year(s) old. </div
>
我们可以直接创建具有值的属性的对象吗?
我知道TypeScript
主要与type
有关。
但想知道是否还有其他东西,以及是否有人知道某些东西。
如果您想展示一些东西,您可以使用这个塞子: Plunker
您还可以在Angular2中使用文字对象,例如Angular1。 由于Angular2可与TypeScript一起使用,因此您可以利用其强类型。 这样,您可以指定属性和参数的类型。 现在无法进行检查,如果使用了不正确的类型,这将导致类型错误。
import {LoginModel} from '../models.ts';
export class Test {
user:LoginModel = new LoginModel()
constructor() {
this.user.name = 'micronyks';
this.user.age = 27;
this.someMethod(this.user);
}
someMethod(user:LoginModel) {
// ...
}
}
另一点与依赖注入有关,因为Angular2可以依靠类型来知道要注入哪个实例...否则,您需要使用@Inject
。
在您的IDE中也有影响。 因为如果定义类型而不是没有类型或any
类型,就可以完成。
实际上,甚至可以混合一些东西:
interface INumbersOnly {
[key: string]: number;
}
var x: INumbersOnly = {
num: 1, // works fine
str: 'x' // will give a type error
};
所以我想说,您可以自由地做自己想做的事;-)
有关详细信息,请参阅此问题:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.