SrollToTop 方法不适用于 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;
}

为什么离子-fab-button不'不固定在离子4弹窗内?

运行正常

现在我有了在ts文件中滚动到顶部的方法。

fabbutton.component.ts

export class FabbuttonComponent {
@ViewChild(IonContent, { static: false }) content: IonContent;
scrollToTop() {
this.content.scrollToTop(1500);
}
}

我在我的主页中像这样使用选择器。

home。

<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中注入了组件。模块文件。

当我测试应用程序时,我得到以下错误:

核心。mjs:6494 ERROR TypeError:不能读取未定义的属性(读"scrollToTop")在FabbuttonComponent。scrollToTop (fabbutton.component.ts 14:18):在FabbuttonComponent_Template_ion_fab_button_click_2_listener (html:3:56)在executeListenerWithErrorHandling (core. js:15031:1)在wrapListenerIn_markDirtyAndPreventDefault (core.mjs:15069:1)在HostElement。(platform-browser.mjs: 466:38)在_ZoneDelegate.push.3484._ZoneDelegate。invokeTask (zone.js 443:1):在对象。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 [as invoke] (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() ;
}
}

home。

...
<app-fabbutton (onClick)="scrollToTop()"></app-fabbutton>
...

Home.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>

测试后,它像一个魅力!

最新更新