0

I'm using Angular 2 in an Ionic 2 application. I would like to get a value from a template to use in my component. I know how to define a variable in my component and then use it in my template, but I'm looking for the other way around. Here's what I mean:

Component:

@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()...

}

I want to hardcode the value of [route] in the template, and then get that value in my component as this.route. [route] does not have to be on ion-list, it can be anywhere as long as I can get it into my component.

Thanks in advance.

1 Answer 1

2

You want to use a ViewChild.

See this demo plunker: 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 {}
Sign up to request clarification or add additional context in comments.

2 Comments

Note: remove the @NgModule and selector-tag, these don't work within ionic and can cause your application to be bugged
That works great, thank you so much! Only thing I had to do was add a default argument to avoid errors: this._getAttributeValue(this.h2, 'route', '/default/route/here')

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.