Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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: http://plnkr.co/edit/4FoFNBFsOEvvOkyfn0lw?p=preview

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

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

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

Thanks!

like image 323
Tomino Avatar asked Feb 25 '16 12:02

Tomino


2 Answers

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

  • Angular 2 input parameters on root directive

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>
like image 189
Thierry Templier Avatar answered Oct 18 '22 05:10

Thierry Templier


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>
like image 18
Germanaz0 Avatar answered Oct 18 '22 05:10

Germanaz0