Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Input binding does not work [duplicate]

Tags:

angular

index.html:

  <app [myname]="some_name"></app>

app.component.ts:

  import {Component, Input, Output} from '@angular/core';

  @Component({
    selector: 'app',
    template: '<span>{{myname}}</span>'
  })

  export class CupBuyComponent {
      @Input() myname: String;

      constructor(){
          console.log(this.myname);
      }
  }

JS console says undefined. How can I get variables from .html file to send it to component?

like image 558
Rattrap Avatar asked Sep 21 '16 10:09

Rattrap


2 Answers

Update

The reason why this is not working is that your index.html in which you place the is not an angular component. Because of this, Angular won't compile this element. And Angular does not read attribute values during runtime, only during compile time, as otherwise we would get a performance hit.

https://github.com/angular/angular/issues/1858#issuecomment-151326461

This will do what you want:

index.html

<app myname="some_name"></app>

Root component

export class CupBuyComponent {
  @Input() myname: String;

  constructor(elm: ElementRef){
    this.myname = elm.nativeElement.getAttribute('myname');
  }
}

Also if you want pass data as object you can take a look at this question

  • Passing server parameters to ngModule after RC5 upgrade

Original

If you want to pass data as text then it should be

<app [myname]="'some_name'"></app>

or

<app myname="some_name"></app>
like image 128
yurzui Avatar answered Sep 30 '22 22:09

yurzui


IMPORTANT

I explained below what's wrong with your binding, but even if you use the code I provided it won't work because you are trying to pass an input to the component you are bootstraping (root component), which is not possible.

If you want to pass string some_name to myname input variable, you should to it without []:

<app myname="some_name"></app>

If you do it with [] like you did, it looks for variable named some_name in your component which you don't have and that's why you get undefined in your console.

like image 37
Stefan Svrkota Avatar answered Oct 01 '22 00:10

Stefan Svrkota