BoomBoomBoom
BoomBoomBoom

Reputation: 219

Angular 2 external inputs

Please can you help? Just starting with Angular 2 and having the following issue.

My component is below:

@Component({
    selector: 'myapp',
    inputs: ['mynumber']
})
@View({
    template: `<p>The next number is {{ mynumber + 1 }}</p>'
})
export class App {
    mynumber: number;
}
bootstrap(App);

Inside my HTML:

<myapp [mynumber]='41'></myapp>

But when run I get the following:

The next number is NaN

It looks simple but I am missing something. What I am trying to achieve is passing a value from outside the app into it.

Thanks.

Upvotes: 20

Views: 6196

Answers (4)

Kyle_jumpen
Kyle_jumpen

Reputation: 111

For those using angular 4 : If you decide to use it as an attribute like that

    <myapp mynumber='41'></myapp>

You could just use the annotation @Attribute like that :

class Component {
    constructor(@Attribute('attributeName') public param:String){
        /** some process with your injected param **/
    }
}

Tested and worked successfully in my app.

Found the way there : https://gillespie59.github.io/2015/10/08/angular2-attribute-decorator.html

Upvotes: 2

Dion
Dion

Reputation: 71

Update to answers using ElementRef: use Renderer.selectRootElement instead. Anyone trying to use ElementRef.nativeElement is probably seeing various warnings about how this is a last resort etc. Here is a modified, safer version.

constructor( renderer: Renderer ){
  let rootElement = renderer.selectRootElement('app-root');
  this.whateverInput = rootElement.getAttribute('my-attribute');
}

Upvotes: 7

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657396

A workaround is reading it directly using ElementRef:

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

and use it like

<myapp mynumber='41'></myapp>

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

Upvotes: 8

alexpods
alexpods

Reputation: 48505

You can't specify property bindings (inputs) for the root component of your application. If you really want to specify some binding for it you should use additional component. See this plunkers.

import {Component, Input} from 'angular2/angular2'

@Component({
  selector: 'myapp',
  template: `   
    <p>The next number is {{ mynumber + 1 }}</p>
  `
})
class App {
  @Input() mynumber: number;
}

@Component({
  selector: 'root',
  directives: [App],
  template: `
    <myapp [mynumber]="41"></myapp>
  `
})
export class Root {}

Upvotes: 11

Related Questions