问题
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