Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 external inputs

Tags:

angular

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.

like image 403
BoomBoomBoom Avatar asked Oct 15 '15 15:10

BoomBoomBoom


People also ask

What is @input and @output in Angular 2?

The above pattern — passing data in through an “input” property and sending data out through an “output” event — is the primary way to share data between Angular 2 components.

What does @input do in Angular?

Use the @Input() decorator in a child component or directive to let Angular know that a property in that component can receive its value from its parent component. It helps to remember that the data flow is from the perspective of the child component.

Can't bind to since it isn't a known property of?

This error often means that you haven't declared the directive "x" or haven't imported the NgModule to which "x" belongs. Perhaps you declared "x" in an application sub-module but forgot to export it. The "x" class isn't visible to other modules until you add it to the exports list.


2 Answers

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 {}
like image 169
alexpods Avatar answered Nov 01 '22 04:11

alexpods


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

like image 39
Günter Zöchbauer Avatar answered Nov 01 '22 03:11

Günter Zöchbauer