-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathapp.component.ts
More file actions
59 lines (53 loc) · 1.25 KB
/
Copy pathapp.component.ts
File metadata and controls
59 lines (53 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { NgIf } from '@angular/common';
import { Component, computed, inject, NgZone, signal } from '@angular/core';
import { fromEvent } from 'rxjs';
@Component({
standalone: true,
imports: [NgIf],
selector: 'app-root',
template: `
<div>Top</div>
<div>Middle</div>
<div>Bottom</div>
<button (click)="goToTop()" *ngIf="displayButton()">Top</button>
`,
styles: [
`
:host {
height: 1500px;
display: flex;
flex-direction: column;
justify-content: space-between;
button {
position: fixed;
bottom: 1rem;
left: 1rem;
z-index: 1;
padding: 1rem;
}
}
`,
],
})
export class AppComponent {
private ngZone = inject(NgZone);
private shouldDisplayButton = signal(false);
displayButton = computed(() => this.shouldDisplayButton());
constructor() {
this.ngZone.runOutsideAngular(() => {
fromEvent(window, 'scroll').subscribe(() => {
const shouldShow = window.pageYOffset > 50;
if (this.shouldDisplayButton() !== shouldShow) {
this.shouldDisplayButton.set(shouldShow);
}
});
});
}
goToTop() {
window.scroll({
top: 0,
left: 0,
behavior: 'smooth',
});
}
}