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

x33g5p2x  于 2023-01-21  发布在  TypeScript
关注(0)|答案(1)|浏览(215)

我正在尝试实现这个"滚动回到顶部"按钮在这里找到:
https://www.w3schools.com/howto/howto_js_scroll_to_top.asp
我是Angular的新手,我尝试实现它时总是遇到错误和类型错误。
这是我的代码:

    • 主页.组件. 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>
    • 主页.组件. 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(){

    window.onscroll = this.scrollFunction();
}

但那也没用。
我如何实现这一点?我做错了什么,你如何修复它?

toe95027

toe950271#

好吧,看起来问题是你试图通过这样做来声明你的组件的一个窗口属性:

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
祝你好运:)

相关问题