Angular 2从模板获取组件变量

Angular 2从模板获取组件变量,angular,ionic2,Angular,Ionic2,我在离子2应用程序中使用Angular 2。我想从模板中获取一个值,以便在我的组件中使用。我知道如何在组件中定义变量,然后在模板中使用它,但我正在寻找另一种方法。我的意思是: 组成部分: @Component({ template: '<ion-list [route]="path/on/site"> <ion-item *ngFor="let item of items"> {{title}}

我在离子2应用程序中使用Angular 2。我想从模板中获取一个值,以便在我的组件中使用。我知道如何在组件中定义变量,然后在模板中使用它,但我正在寻找另一种方法。我的意思是:

组成部分:

@Component({
  template: '<ion-list [route]="path/on/site">
                <ion-item *ngFor="let item of items">
                  {{title}}
                </ion-item>
            </ion-list>'
})
export class List {
  route: string;

  constructor() {

    this.route = // should get value of [route] in template;
    this.loadData( this.route );

  }

  loadData()...

}
@组件({
模板:'
{{title}}
'
})
导出类列表{
路径:字符串;
构造函数(){
this.route=//应获取模板中[route]的值;
this.loadData(this.route);
}
loadData()。。。
}
我想在模板中硬编码[route]的值,然后在我的组件中将该值作为this.route。[route]不必在离子列表中,只要我能将其放入我的组件中,它就可以在任何地方


提前感谢。

您想使用
ViewChild

请参阅此演示plunker:

从'@angular/core'导入{Component,NgModule,ViewChild,ElementRef}
从“@angular/platform browser”导入{BrowserModule}
@组成部分({
//选择器:'我的应用',//不要在Ionic中使用
模板:`
你好{{name}
`,
})
导出类应用程序{
@ViewChild('headerWithRoute')h2:ElementRef;
构造函数(){
this.name='Angular2'
}
private _getAttributeValue(元素:ElementRef,名称:string,defaultVal:any):any{
让attribute=element.nativeElement.attributes.getNamedItem(名称);
如果(!attribute)返回defaultVal;
返回attribute.nodeValue;
}
ngAfterViewInit(){
//ViewChild仅在此事件之后有效!!
log(this._getAttributeValue(this.h2,'route');
}
}
//不要在离子液体中使用
//@NGD模块({
//导入:[BrowserModule],
//声明:[App],
//引导:[应用程序]
//})
//导出类AppModule{}

您想使用一个
视图子对象

请参阅此演示plunker:

从'@angular/core'导入{Component,NgModule,ViewChild,ElementRef}
从“@angular/platform browser”导入{BrowserModule}
@组成部分({
//选择器:'我的应用',//不要在Ionic中使用
模板:`
你好{{name}
`,
})
导出类应用程序{
@ViewChild('headerWithRoute')h2:ElementRef;
构造函数(){
this.name='Angular2'
}
private _getAttributeValue(元素:ElementRef,名称:string,defaultVal:any):any{
让attribute=element.nativeElement.attributes.getNamedItem(名称);
如果(!attribute)返回defaultVal;
返回attribute.nodeValue;
}
ngAfterViewInit(){
//ViewChild仅在此事件之后有效!!
log(this._getAttributeValue(this.h2,'route');
}
}
//不要在离子液体中使用
//@NGD模块({
//导入:[BrowserModule],
//声明:[App],
//引导:[应用程序]
//})
//导出类AppModule{}

注意:删除
@NgModule
选择器
-标记,这些标记在爱奥尼亚内部不起作用,可能会导致应用程序出现错误。非常感谢!我唯一要做的就是添加一个默认参数来避免错误:this.\u getAttributeValue(this.h2,'route','default/route/here')注意:删除
@NgModule
选择器
-标记,它们在ionic中不起作用,可能会导致应用程序出错。非常感谢!我唯一要做的就是添加一个默认参数来避免错误:this.\u getAttributeValue(this.h2,'route','/default/route/here')