Access parent content within child component or better way

馋奶兔 提交于 2020-01-03 00:02:24

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/46192659/access-parent-content-within-child-component-or-better-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!