[英]Checking an event only in one page of the app in angular2
我正在用angular 4.0開發我的第一個應用程序。
我的問題很簡單,但是我想知道是否有最佳實踐來解決我的問題。
我有一個標頭,其位置為:“固定”,當用戶滾動頁面時,此元素通過動態添加“小”類來更改其某些屬性(高度,背景尺寸..)。
這是我的組成部分
import {Component, OnInit, HostListener} from '@angular/core';
@Component({
selector: 'my-header',
templateUrl: './my-header.component.html',
styleUrls: ['./my-header.component.css']
})
export class HeaderComponent implements OnInit {
scrollState: boolean;
constructor() { }
ngOnInit() {
this.scrollState = false;
}
@HostListener('window:scroll', [])
toggleScrollState() {
if(window.pageYOffset == 0){
this.scrollState = false;
}
else{
this.scrollState = true;
}
}
}
這是HTML
<header class="bk-blue clearfix" [ngClass]="{small: scrollState}">
<a class="sx" href="#">Login</a>
<a class="dx arrow-down"></a>
<a class="dx" href="#">It</a>
</header>
一切正常,但這只能在主頁中進行 。 在另一頁中,標頭元素應該已經處於“小”狀態,而沒有基於滾動事件的任何DOM操作。
我正在考慮檢查當前路由以設置其他變量(如果當前路由與主頁路徑匹配,則為false,否則為true),然后將其與scrollState放在OR中。 像這樣:
<header class="bk-blue clearfix" [ngClass]="{small: notHome || scrollState}">
但是,這樣做無法避免以降低性能的方式調用偵聽器。
對您來說,即使在不必要的內部頁面中也避免調用偵聽器的最佳方法是什么?
好吧,我會使用ActivatedRouteSnapshot
做到這一點
@Component({...})
class Header implements OnInit {
readonly snapshot: ActivatedRouteSnapshot = null;
constructor(private route: ActivatedRoute) {
this.snapshot = route.snapshot;
}
ngOnInit() {
// if this.snapshot is HOMEPAGE
// then
// subscribe to the scroll and switch class when you need.
}
}
您還可以在route.data
上設置一個屬性,該屬性告訴您是否設置標題的動畫。
const routes: Routes = [
{
path: '',
component: HomeRouteComponent,
data: { ANIMATE_HEADER: true }
}
];
// header.ts
ngOnInit() {
if(this.snapshot.data.ANIMATE_HEADER) {
// do stuff here
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.