Angular材质CDK提供了一个Directive CdkScrollable,它允许您监听特定容器的ScrollEvent。
我现在正在尝试访问MatSidenavContent的CdkScrollable,它是默认添加的。
但是,我的@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-Directive。
我现在的问题是:
是否可以访问该Directive?如果可以,访问方式是什么?
发布于 2018-04-27 21:53:10
前段时间我在@angular/material上发布了一个问题,现在他们公开了CdkScrollable-Instance。
要使用它,您需要使用@ViewChild(MatSidenavContainer访问MatSidenavContainer。此实例有一个公共成员CdkScrollable实例,即scrollable。
可以在here中找到一个示例
编辑:由于示例不是非常完整,一些人在实现它时遇到了困难,我将在这里编写我自己的示例:
HTML
<mat-sidenav-container>
<mat-sidenav #sidenav>
Sidenav Content
</mat-sidenav>
<div>
Main Content
</div>
</mat-sidenav-container>TypeScript:
import { Component, AfterViewInit, ViewChild } from '@angular/core';
import { MatSidenavContainer } from '@angular/material';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
@ViewChild(MatSidenavContainer) sidenavContainer: MatSidenavContainer;
constructor() {
}
ngAfterViewInit() {
console.log(this.sidenavContainer.scrollable);
}
}重要
<mat-sidenav-content>。此标记是自动生成的,并且附加了cdkScrollable指令。如果您在自己的模板中使用<mat-sidenav-content>,则scrollable将是undefined.AfterViewInit而不是OnInit。据我所知,@ViewChild是在AfterViewInit中解决的,OnInit可能还为时过早。发布于 2018-06-12 16:38:14
将
mat-sidenav-content的
<mat-sidenav-content cdkScrollable> </mat-sidenav-content>
根组件中的
a)从@angular/cdk/overlay注入ScrollDispatcher并订阅滚动:
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已弃用
https://stackoverflow.com/questions/47528852
复制相似问题