CT14.IT
CT14.IT

Reputation: 1747

Angular 2 Access Component Defined by Template

I'm using Ionic as an example for this, but I figure it's a general Angular 2 question.

page1.ts

import {Page} from 'ionic-angular';

@Page({
  templateUrl: 'build/pages/page1/page1.html'
})
export class Page1 {
  constructor() {

  }
}

page1.html

<ion-navbar *navbar>
  <ion-title>Tab 1</ion-title>
</ion-navbar>

<ion-content padding class="page1">
  <ion-slides pager>
     <ion-slide>
       <h3>Thank you for choosing the Awesome App!</h3>
       <p>
         The number one app for everything awesome.
       </p>
     </ion-slide>
     <ion-slide>
       <h3>Using Awesome</h3>
        <div id="list">
          <h5>Just three steps:</h5>
          <ol>
            <li>Be awesome</li>
            <li>Stay awesome</li>
            <li>There is no step 3</li>
          </ol>
        </div>
     </ion-slide>
     <ion-slide>
       <h3>Any questions?</h3>
     </ion-slide>
   </ion-slides>
</ion-content>

How do I programatically reference the ion-slides object from the constructor of the Page1 class?

I had assumed via some sort of #reference but I'm not sure of the syntax

Upvotes: 0

Views: 134

Answers (2)

user13136
user13136

Reputation: 74

Yes, it's an angular question.You can use @ViewChild decorator to access child component. like:

@ViewChild(CountdownTimerComponent)
  private _timerComponent:CountdownTimerComponent;

See the angular2 doc for the detail, not to hard.

https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-view-child

PS. if you have more than on components in same type like Button, use

@ViewChildren(Button) buttons: QueryList<Button>;

Upvotes: 2

Mark Rajcok
Mark Rajcok

Reputation: 364727

If ion-slides is a component or a directive, and there is only one instance in the template, use @ViewChild:

@ViewChild(IonSlides) ionSlides:IonSlides;

This assumes the component class name is IonSlides.

this.ionSlides will not be available in the constructor. It will be available in lifecycle hook ngAfterViewInit(), as documented in the ViewChild API page:

ngAfterViewInit() {
   console.log(this.ionSlides);
}

Upvotes: 3

Related Questions