8

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?

Rattrap
  • 295
  • 4
  • 13

3 Answers3

14

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


Original

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

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

or

<app myname="some_name"></app>
yurzui
  • 205,937
  • 32
  • 433
  • 399
2

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.

Stefan Svrkota
  • 48,787
  • 9
  • 98
  • 87
1

Its accessible in and after this event:

ngOnInit() { ... here ... }

and as the others already mentioned.. if you are using the [myname]="variable or expression()" syntax, inside the "" need to be a variable or an expression of your component..

If you are using this syntax myname="anyStringHere" you can paste only a string there..

slaesh
  • 16,659
  • 6
  • 50
  • 52