gpt4 book ai didi

Angular-Material Sidenav cdkScrollable

转载 作者:太空狗 更新时间:2023-10-29 17:06:37 28 4
gpt4 key购买 nike

Angular Material CDK提供了一个DirectiveCdkScrollable,可以监听特定容器的ScrollEvent
我现在正在尝试访问默认添加的 MatSidenavContentCdkScrollable
但是我的 @ViewChild(CdkScrollable)@ContentChild(CdkScrollable) 始终未定义。

我的 Component 看起来像这样:

<mat-sidenav-container>
<mat-sidenav>Sidenav content</mat-sidenav>
<div>Main content</div>
</mat-sidenav-container>

生成的 DOM 看起来像这样:

<mat-sidenav-container>
<div class="mat-drawer-backdrop"></div>
<div tabindex="-1" class="cdk-visually-hidden cdk-focus-trap-anchor"></div>
<mat-sidenav>Sidenav content</mat-sidenav>
<mat-sidenav-content cdkScrollable>
<div>Main content</div>
</mat-sidenav-content>
</mat-sidenav-container>

自动生成的 mat-sidenav-content Component 使用了我需要访问的 CdkScrollable 指令。< br/>我现在的问题是:
是否可以访问该 Directive,如果可以,如何访问?

最佳答案

  1. 添加到您的应用模块导入:ScrollDispatchModule .
  2. 添加cdkScrollable给你的mat-sidenav-content :

<mat-sidenav-content cdkScrollable> </mat-sidenav-content>

  1. 在你的根组件中:

a) 注入(inject) ScrollDispatcher来自 @angular/cdk/overlay并订阅滚动:

constructor(public scroll: ScrollDispatcher) {

this.scrollingSubscription = this.scroll
.scrolled()
.subscribe((data: CdkScrollable) => {
this.onWindowScroll(data);
});
}

c) 滚动时做一些事情,例如检查偏移量

private onWindowScroll(data: CdkScrollable) {
const scrollTop = data.getElementRef().nativeElement.scrollTop || 0;
if (this.lastOffset > scrollTop) {
// console.log('Show toolbar');
} else if (scrollTop < 10) {
// console.log('Show toolbar');
} else if (scrollTop > 100) {
// console.log('Hide toolbar');
}

this.lastOffset = scrollTop;
}

文档:https://material.angular.io/cdk/scrolling/api

更新 Angular 9:

使用 import {ScrollingModule} from '@angular/cdk/scrolling' , ScrollDispatchModule已弃用

关于Angular-Material Sidenav cdkScrollable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47528852/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com