当 ngif 来自 scrollDispatcher 时,变量不起作用

When ngif from scrollDispatcher, the variable not working

在 angular 中,我使用 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
    });
}

当我滚动时,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必须为真,也是是的,但是 *ngIf="sectionStickyTitleState"(flag) 总是无法响应。

这真的让我很难理解,因为 console.log 总是表示标志为真。

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

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

根据docs

in order to avoid hitting change detection for every scroll event, all of the events emitted from this stream will be run outside the Angular zone. If you need to update any data bindings as a result of a scroll event, you have to run the callback using 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 模板绑定不会更新,即使它打印控制台。

希望对您有所帮助。