【问题标题】:Angular 2 get component variable from templateAngular 2 从模板中获取组件变量
【发布时间】:2016-09-20 20:56:18
【问题描述】:

我在 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 上,只要我可以将它放入我的组件中,它就可以在任何地方。

提前致谢。

【问题讨论】:

    标签: angular ionic2


    【解决方案1】:

    您想使用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 {}
    

    【讨论】:

    • 注意:删除 @NgModuleselector-tag,它们在 ionic 中不起作用,可能会导致您的应用程序出现错误
    • 效果很好,非常感谢!我唯一要做的就是添加一个默认参数以避免错误:this._getAttributeValue(this.h2, 'route', '/default/route/here')
    猜你喜欢
    • 2016-08-04
    • 2017-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-27
    • 2016-04-29
    • 1970-01-01
    • 2017-09-29
    相关资源
    最近更新 更多