Angular 2 从模板中获取组件变量

Angular 2 get component variable from template

我在 Ionic 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()...

}

我想在模板中硬编码 [route] 的值,然后在我的组件中获取该值作为 this.route。 [route] 不必在 ion-list 上,它可以在任何地方,只要我可以将它放入我的组件即可。

提前致谢。

您想使用 ViewChild

查看此演示插件:https://plnkr.co/edit/AkcKeInPxLRgNBPKiglk?p=preview

import {Component, NgModule, ViewChild, ElementRef} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  //selector: 'my-app', // do NOT use in Ionic
  template: `
    <div>
      <h2 #headerWithRoute route="/any/route/here">Hello {{name}}</h2>
    </div>
  `,
})
export class App {

  @ViewChild('headerWithRoute') h2: ElementRef;

  constructor() {
    this.name = 'Angular2'
  }

  private _getAttributeValue(element: ElementRef, name: string, defaultVal: any): any {
    let attribute = element.nativeElement.attributes.getNamedItem(name);
    if (!attribute) return defaultVal;
    return attribute.nodeValue;
  }

  ngAfterViewInit() {
    // viewchilds are only valid after this event !!

    console.log(this._getAttributeValue(this.h2, 'route'));
  }
}

// do NOT use in Ionic
//@NgModule({
//  imports: [ BrowserModule ],
//  declarations: [ App ],
//  bootstrap: [ App ]
//})
//export class AppModule {}