簡體   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