访问子组件内的父内容或更好的方式 [英] 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(孩子)
<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.content
是 undefine
。你能告诉我怎么做得好吗?
Then it shows below error since this.content
is undefine
. Can you tell me how to do it properly?
推荐答案
您可以将父项注入子构造函数,如下所示:
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);
}
}
但请注意,现在你的 ProjectComponent
只能在< ion-content>
组件中使用。除非你在构造函数中将它标记为 @Optional()
。
But note that now your ProjectComponent
can only be used inside a <ion-content>
component. Unless you mark it as @Optional()
inside the constructor.
这篇关于访问子组件内的父内容或更好的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文