访问子组件内的父内容或更好的方式

时间:2017-09-13 08:32:33

标签: angular typescript ionic3

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(孩子)

<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);
        }
}

然后它显示以下错误,因为this.contentundefine。你能告诉我怎么做得好吗?

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以将父项注入子构造函数,如下所示:

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);
    }
}

但请注意,现在您的ProjectComponent只能在<ion-content>组件中使用。除非你在构造函数中将其标记为@Optional()