ion-slides 组件在底层使用了 Swiper 库。Swiper 的部分初始化代码取决于知道幻灯片容器的宽度,以及clientWidth
用于获取它的代码。由于菜单以 开头display:none
,因此检索到的宽度始终为零,并且初始化代码会交给您。
您可以通过display:block
在 Swiper 初始化时临时设置来解决此问题。我在组件内有我的侧边菜单,因此您可能需要根据您的情况调整此代码:
应用程序.html:
<sidebar [content]="content"></sidebar>
<ion-nav #content [root]="rootPage" swipeBackEnabled="false"></ion-nav>
边栏.html:
<ion-menu [content]="content" swipeEnabled="false">
<ion-content>
<ion-slides pager>
<ion-slide>
<h2>Slide 1</h2>
</ion-slide>
<ion-slide>
<h2>Slide 2</h2>
</ion-slide>
<ion-slide>
<h2>Slide 3</h2>
</ion-slide>
</ion-slides>
</ion-content>
</ion-menu>
sidebar.component.ts:
...
@Component({
selector: 'sidebar',
templateUrl: 'sidebar.html',
})
export class SidebarComponent implements AfterViewInit {
@Input('content') content: NavController;
@ViewChild(Slides) slides: Slides;
@ViewChild(Menu, { read: ElementRef }) menuRef: ElementRef;
// Use Renderer2 instead of direct DOM manipulation through the
// ElementRef.nativeElement.
//
// @see: https://medium.com/@kmathy/angular-manipulate-properly-the-dom-with-renderer-16a756508cba
//
constructor(private renderer: Renderer2) {
}
// ViewChild template references might not be available until
// AfterViewInit lifecycle hook runs.
//
// @see: https://blog.angular-university.io/angular-viewchild/
//
ngAfterViewInit() {
this.renderer.setStyle(this.menuRef.nativeElement, 'display', 'block');
setTimeout(() => {
// Swiper init has its own ngAfterViewInit code that delays 300ms
// before running. Don't remove the 'display' style until after that.
this.renderer.removeStyle(this.menuRef.nativeElement, 'display');
}, 310);
}
}