在角度中,我使用scrollDispatcher(检查滚动)更改html DOM上的变量标志,但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
});
}
Run Code Online (Sandbox Code Playgroud)
当我滚动时,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);
}
Run Code Online (Sandbox Code Playgroud)
我重新编辑了问题,目的是一样的,flag无法被html识别,当#sectionh1的高度小于21时,flag必须为true,也是true,但是*ngIf="sectionStickyTitleState" (flag)总是无法回应。
这真的让我很难理解,因为 console.log 总是意味着 flag 为 true。
根据文档
为了避免对每个滚动事件进行更改检测,从此流发出的所有事件都将在 Angular 区域之外运行。如果您需要因滚动事件而更新任何数据绑定,则必须使用 NgZone.run 运行回调。
因此,请执行以下操作;
constructor(private scrollDispatcher: ScrollDispatcher, private zone: NgZone){}
ngOnInit() {
this.scrollDispatcher.scrolled().subscribe(() => {
this.zone.run(() => {
this.setSectionStickyTitle();
});
});
}
Run Code Online (Sandbox Code Playgroud)
我还在这里创建了一个演示https://stackblitz.com/edit/angular-msn4ma
在上面的演示中,当您滚动body或div1模板绑定正确更新时。但是,如果您滚动div2模板绑定,即使它打印控制台也不会更新。
希望能帮助到你。
| 归档时间: |
|
| 查看次数: |
2094 次 |
| 最近记录: |