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?
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With