【问题标题】:When ngif from scrollDispatcher, the variable not working当来自 scrollDispatcher 的 ngif 时,变量不起作用
【发布时间】: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 嗨,我重新编辑了我的问题,具体示例有更多细节。谢谢。

标签: angular subscribe


【解决方案1】:

我建议在您的代码中进行一些更改,使用 this 而不是 let 并使用箭头函数

constructor( private scrollDispatcher: ScrollDispatcher){
    this.scrollDispatcher.scrolled().subscribe() => {
      this.scrollState = true;
      console.log('now scrolling!', this.scrollState ); 
    });
}

【讨论】:

  • 谢谢,我换了一个箭头,但 ngif 还是不行 :(
  • 在 html 上试试 {{scrollState}} 看看
  • 其实滚动的时候做出反应并不是初衷。本来有offsetTop来判断其他DOM的,但是也没有用,所以只是想确认一下是否还有其他的可能。就像“ if(offset
【解决方案2】:

根据docs

为了避免对每个滚动事件进行更改检测,所有 从此流中发出的事件将在 Angular 之外运行 区。如果由于滚动而需要更新任何数据绑定 事件,你必须使用 NgZone.run 运行回调。

那么,请按照以下方式进行;

constructor(private scrollDispatcher: ScrollDispatcher, private zone: NgZone){}

ngOnInit() {
  this.scrollDispatcher.scrolled().subscribe(() => {
    this.zone.run(() => {
      this.setSectionStickyTitle();
    });
  });
}

我还在这里创建了一个演示 https://stackblitz.com/edit/angular-msn4ma

在上面的演示中,当您滚动 bodydiv1 时,模板绑定会正确更新。但是如果你滚动div2,即使它打印控制台,模板绑定也不会更新。

希望对你有帮助。

【讨论】:

  • 感谢您的准确解释,确实有效,我会记住的,再次感谢您。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-09
  • 2016-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多