【发布时间】:2019-11-15 23:18:41
【问题描述】:
在 Angular 中,我在 html DOM 使用 scrollDispatcher(checking scrolling) 更改变量标志,但是 DOM(ngif) 不起作用,有我的测试代码:
// html
<div *ngIf="scrollState">
scrolling!
</div>
// TS
import { ScrollDispatcher } from '@angular/cdk/scrolling';
...
scrollState = false;
...
constructor( private scrollDispatcher: ScrollDispatcher){
let self = this;
this.scrollDispatcher.scrolled().subscribe( function () {
self.scrollState = true;
console.log('now scrolling!', self.scrollState );
//checking scrollState, it's true
});
}
当我滚动时,DOM 不显示,但我检查 self.scrollState 是真的,为什么?看不懂,请帮帮我,谢谢。
具体例子
//html
<div class="sectionStickyTitle" *ngIf="sectionStickyTitleState">
<h2>Test new title</h2>
</div>
<h1 class="section-h1" #sectionh1>I'm check top target</h1>
//TS
import { ScrollDispatcher } from '@angular/cdk/scrolling';
...
@ViewChild('sectionh1') sectionh1: ElementRef;
sectionStickyTitleState = false;
sectionhOffsetTop: number;
...
constructor(private scrollDispatcher: ScrollDispatcher, ...){
}
ngOnInit(){
...
this.scrollDispatcher.scrolled().subscribe(() => this.setSectionStickyTitle());
}
...
setSectionStickyTitle() {
this.sectionhOffsetTop = this.sectionh1.nativeElement.getBoundingClientRect().top;
this.sectionStickyTitleState = (this.sectionhOffsetTop <= 21) ? true : false;
console.log('sectionStickyTitleState --> ', this.sectionStickyTitleState);
console.log('sectionhOffsetTop --> ', this.sectionhOffsetTop);
}
我重新编辑了问题,目的还是一样,flag不能被html识别,当#sectionh1的高度小于21时,flag必须为true,也为true,但是*ngIf= "sectionStickyTitleState"(flag) 总是无法响应。
这真的让我很难理解,因为 console.log 总是意味着 flag 为真。
【问题讨论】:
-
你能详细说明你到底想做什么吗?你想捕获某个元素或 DOM 中的任何元素或只是文档/窗口上的滚动事件吗?还有你在处理事件时会做什么?
-
@ysf 嗨,我重新编辑了我的问题,具体示例有更多细节。谢谢。