index.html:
<app [myname]="some_name"></app>
应用程序组件.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 控制台显示未定义。如何从 .html 文件中获取变量以将其发送到组件?
更新
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
这会做你想做的:
index.html
<app myname="some_name"></app>
根组件
export class CupBuyComponent {
@Input() myname: String;
constructor(elm: ElementRef){
this.myname = elm.nativeElement.getAttribute('myname');
}
}
此外,如果你想将数据作为对象传递,你可以看看这个问题
原创
如果你想将数据作为文本传递,那么它应该是
<app [myname]="'some_name'"></app>
或
<app myname="some_name"></app>