繁体   English   中英

如何使用Angular中的“window”属性?

[英]How to use the "window" property in Angular?

我正在尝试实现此处的“滚动回到顶部”按钮:

https://www.w3schools.com/howto/howto_js_scroll_to_top.asp


我是 Angular 的新手,我尝试实现它时不断出现错误和类型错误。

这是我的代码:

home.component.html

<div class="country-card-container">
   <button (click)="topFunction()" class="scroll-top">TOP</button>
   <app-country-card *ngFor="let country of displayCountries" [country]="country" class="country-cards"></app-country-card>
</div>

主页.component.ts

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.sass']
})
export class HomeComponent {

    mybutton = document.getElementsByClassName("scroll-top");
    
    // When the user scrolls down 20px from the top of the document, show the button
    window.onscroll = this.scrollFunction();
    
    scrollFunction() {
      if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
        this.mybutton.style.display = "block";
     } else {
        this.mybutton.style.display = "none";
     }
    }
    
    // When the user clicks on the button, scroll to the top of the document
    topFunction() {
      document.body.scrollTop = 0; // For Safari
     document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
    }
}

我收到错误:

Unexpected keyword or identifier.ts(1434)

Member 'window' implicitly has an 'any' type.ts(7008)

Cannot find name 'scrollFunction'.ts(2304)

Property 'style' does not exist on type 'HTMLCollectionOf<Element>'.ts(2339)

我也试过把

window.onscroll = this.scrollFunction();

在 ngOnInit 中是这样的:

ngOnInit(){

    window.onscroll = this.scrollFunction();
}

但这也不管用。


我该如何实施? 我做错了什么,你是如何解决的?

好吧,看起来问题在于您尝试通过执行以下操作来声明组件的 window 属性:

export class HomeComponent {
  // this code is not valid, because you try to declare a class property here, not to get the window reference
  window.onscroll = this.scrollFunction();
}

Angular 有一个专门用于这些目的的指令,称为@HostListener 我建议你考虑一下。

@Component({...})
export class HomeComponent {
  @HostListener('window:scroll', ['$event'])
  onWindowScroll(event: Event) {
    // do whatever you want here, including manipulations with the window object as it's available here
    console.log(window);
  }
}

这里参考官方文档: https://angular.io/api/core/HostListener

祝你好运:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM