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

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


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>


You should use @Input decorator.

This is an example:

import { Component, Input } from '@angular/core';@Component({    selector: 'user-menu',    templateUrl: 'user-menu.component.html',    styleUrls: ['user-menu.component.scss'],})export class UserMenuComponent {    /**     * userName Current username     */    @Input('userName') userName: string;    constructor() {    }    sayMyName() {        console.log('My name is', this.userName);    }}

And to use it

<user-menu userName="John Doe"></user-menu>


Update

Inputs aren't supported in the root component as a workaround you can use

constructor(elementRef:ElementRef) {  console.log(elementRef.nativeElement.getAttribute('someattribute');}

See also https://github.com/angular/angular/issues/1858

See also the fixed Plunker

original

You need to either use

[property]="value" 

or

property="{{value}}"

or if it's an attribute

[attr.property]="value" 

or

attr.property="{{value}}"