Tomino Tomino - 1 year ago 159
TypeScript Question

Angular2, TypeScript, How to read/bind attribute value to component class (undefined in ngOnInit)

can someone please advice me how to read/bind attribute value to @component class, which seems to be undefined in ngOnInit method?

Here's a plunker demo:

I'd like to read value of "someattribute" attribute

<my-app [someattribute]="'somevalue'">

inside the App class (src/app.ts) ngOninit method.


Answer Source

You can notice that such parameters can't be used for root component. See this question for more details:

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'); 

We need to use the component this way in the HTML file:

<my-app someattribute="somevalue"></my-app>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download