访问子组件中的父内容或更好的方式 [英] 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屋!
查看全文