Sampath
Sampath

Reputation: 65870

Access parent content within child component or better way

parent.html

<ion-content class="project">
  <ion-grid>
    <ion-row class="details">
      <project [data]="data"></project>// this child componet
    </ion-row>    
  </ion-grid>
</ion-content>

project.html (child)

<input currencyMask type="tel" [ngModel]="data?.budget" 
 [options]="{ prefix: '', thousands: ',', decimal: '' }" 
 formControlName="budget" 
 ngModelChange)="data.budget=$event;calculateContingency()" 
 [id]="'yourInputId' + 0" (focus)="scrollTo(0)"/>

project.ts

import { Content } from 'ionic-angular';

    export class ProjectComponent {

        @ViewChild(Content) content: Content;

        scrollTo(index) {
            let yOffset = document.getElementById('yourInputId' + index).offsetTop;
            this.content.scrollTo(0, yOffset + 20);
        }
}

Then it shows below error since this.content is undefine. Can you tell me how to do it properly?

enter image description here

Upvotes: 2

Views: 1262

Answers (1)

n00dl3
n00dl3

Reputation: 21564

You can inject the parent into the child constructor like this :

import { Content } from 'ionic-angular';

export class ProjectComponent {

    constructor(private content:Content){
    }

    scrollTo(index) {
        let yOffset = document.getElementById('yourInputId' + index).offsetTop;
        this.content.scrollTo(0, yOffset + 20);
    }
}

But note that now your ProjectComponent can only be used inside a <ion-content> component. Unless you mark it as @Optional() inside the constructor.

Upvotes: 3

Related Questions