typescript 从 html 模板 [angular] 中的打字稿文件调用变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43468138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
calling variables from typescript file in html template [angular]
提问by user2243952
I just started working with angular after reading the docs. I'm still a newbie.
阅读文档后,我才开始使用 angular。我还是个新手。
Calling arrays in angular2 is simple:
在 angular2 中调用数组很简单:
you just have to use *ngfor item of items and then {{item.name}}.
你只需要使用 *ngfor item of items 然后是 {{item.name}}。
what if I'm calling a single object, string or any, from my ts file . How can I do that?
如果我从我的 ts 文件中调用单个对象、字符串或任何对象会怎样。我怎样才能做到这一点?
I tried :
我试过 :
{{myvariable}}
or
或者
<div ng-init="let x = myvariable"> {{x.name}}</div>
and other stuff but it doesn't work. Thanks in advance.
和其他东西,但它不起作用。提前致谢。
采纳答案by Günter Z?chbauer
{{myvariable.id}} {{myvariable.name}}
or if the variable is not initialized yet when the component is created.
或者如果在创建组件时变量尚未初始化。
{{myvariable?.id}} {{myvariable?.name}}
回答by Abhay
the variable you are trying to access in your template should be available as public property on your component. e.g. in your component if you have myvar as public property with statement like public myvar : any; and then some where in life cycle hooks or other method of component if you assign that to an object e.g. in ngOnInit if you do this.myvar = { p1 : 2 } then you can access properties of myvar in your template like {{myvar.p1}}
您尝试在模板中访问的变量应该可用作组件的公共属性。例如,在您的组件中,如果您将 myvar 作为公共财产,并带有像 public myvar : any; 这样的语句。然后在生命周期钩子或组件的其他方法中的某些位置,如果您将其分配给对象,例如在 ngOnInit 中,如果您执行 this.myvar = { p1 : 2 } 那么您可以在模板中访问 myvar 的属性,例如 {{myvar. p1}}