Angular2,TypeScript,如何将属性值读取/绑定到组件类(在ngOnInit中未定义) [英] Angular2, TypeScript, How to read/bind attribute value to component class (undefined in ngOnInit)
问题描述
有人可以建议我如何将属性值读取/绑定到@component类,这似乎在ngOnInit方法中未定义吗?
can someone please advice me how to read/bind attribute value to @component class, which seems to be undefined in ngOnInit method?
这是一个小样的演示: http://plnkr.co/edit/4FoFNBFsOEvvOkyfn0lw?p=preview
Here's a plunker demo: http://plnkr.co/edit/4FoFNBFsOEvvOkyfn0lw?p=preview
我想读取"someattribute"属性的值
I'd like to read value of "someattribute" attribute
<my-app [someattribute]="'somevalue'">
在App类(src/app.ts)ngOninit方法内部.
inside the App class (src/app.ts) ngOninit method.
谢谢!
推荐答案
您会注意到此类参数不能用于根组件.有关更多详细信息,请参见此问题:
You can notice that such parameters can't be used for root component. See this question for more details:
解决方法在于利用ElementRef
类.它需要注入到您的主要组件中:
The workaround consists in leveraging the ElementRef
class. It needs to be injected into your main component:
constructor(elm: ElementRef) {
this.someattribute = elm.nativeElement.getAttribute('someattribute');
}
我们需要在HTML文件中以这种方式使用组件:
We need to use the component this way in the HTML file:
<my-app someattribute="somevalue"></my-app>
这篇关于Angular2,TypeScript,如何将属性值读取/绑定到组件类(在ngOnInit中未定义)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!