Angular2,TypeScript,如何读取/绑定属性值到组件类(在 ngOnInit 中未定义) [英] Angular2, TypeScript, How to read/bind attribute value to component class (undefined in ngOnInit)

查看:16
本文介绍了Angular2,TypeScript,如何读取/绑定属性值到组件类(在 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?

这是一个plunker演示: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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆