[英]SrollToTop method doesn't work with a component in Ionic 6/Angular
我制作了一个 fabbutton,因此用户可以一键滚动到顶部。 我已经在没有组件的情况下对此进行了测试,并且工作正常。 现在我想将此 fabbutton 用作组件,因为我想在多个页面中使用它。
这是我的组件设置:
fabbutton.component.html
<div class="fixed">
<ion-fab vertical="bottom" horizontal="end" edge slot="fixed">
<ion-fab-button class="toolbar-color" size="small" (click)="scrollToTop()">
<ion-icon name="arrow-up"></ion-icon>
</ion-fab-button>
</ion-fab>
</div>
我使用自定义 css 类使其在用户滚动时保持不变
fabbutton.component.scss
.fixed {
position: fixed;
bottom: 30px;
right: 0;
}
为什么 ion-fab-button 不能固定在 ionic 4 popover 内?
这工作正常。
现在我有方法在 ts 文件中滚动到顶部。
fabbutton.component.ts
export class FabbuttonComponent {
@ViewChild(IonContent, { static: false }) content: IonContent;
scrollToTop() {
this.content.scrollToTop(1500);
}
}
我在主页中使用这样的选择器。
主页.html
<ion-header>
<ion-toolbar>
<ion-buttons slot="start">
<ion-menu-button></ion-menu-button>
</ion-buttons>
<ion-title>Home</ion-title>
</ion-toolbar>
</ion-header>
<ion-content color="secondary" [scrollEvents]="true">
<app-fabbutton></app-fabbutton>
</ion-content>
我还将组件注入到 home.module 文件中。
当我测试应用程序时,我收到以下错误:
core.mjs:6494 错误类型错误:无法在 FabbuttonComponent_Template_ion_fab_button_click_2_listener (template.html:3:56) 在 executeListenerWithErrorHandling (core. mjs:15031:1) 在 HostElement 的 wrapListenerIn_markDirtyAndPreventDefault (core.mjs:15069:1)。 (platform-browser.mjs:466:38) 在 _ZoneDelegate.push.3484._ZoneDelegate.invokeTask (zone.js:443:1) 在 Object.onInvokeTask (core.mjs:25595:1) 在 _ZoneDelegate.push.3484。 _ZoneDelegate.invokeTask (zone.js:442:1) 在 Zone.push.3484.Zone.runTask (zone.js:214:1) 在 ZoneTask.push.3484.ZoneTask.invokeTask [作为调用] (zone.js: 525:1)
我曾尝试将该方法用作父子方法,但它不起作用。 如何在注入页面中使用组件方法? 有人可以指出我正确的方向吗?
jsfiddle: https ://jsfiddle.net/920cagns/
您无法从 fabbutton (子元素)访问离子内容(在本例中为父元素)。 您必须将 EventEmitter 添加到 fabbutton 并从 home.ts 滚动
fabbutton.component.ts
...
export class FabbuttonComponent {
@Output('onClick') onClick = new EventEmitter();
scrollToTop() {
this.onClick.emit() ;
}
}
主页.html
...
<app-fabbutton (onClick)="scrollToTop()"></app-fabbutton>
...
主页.ts
...
@ViewChild(IonContent, { static: false }) content: IonContent;
scrollToTop() {
this.content.scrollToTop(1500);
}
...
我在 fabbutton.component.html 上添加了 scrollToTop() 方法,如下所示:
<div class="fixed">
<ion-fab (click)="scrollToTop()" vertical="bottom" horizontal="end" edge slot="fixed">
<ion-fab-button class="toolbar-color" size="small">
<ion-icon name="arrow-up"></ion-icon>
</ion-fab-button>
</ion-fab>
</div>
经过测试,它就像一个魅力!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.