getCurrentRoute


Show or hide a floating banner on any page depending on what route is currently being displayed by the AppComponent. This approach subscribes to the router's navigation-end event.

import { Router, NavigationEnd } from '@angular/router'

@Component({
    selector: "app-root",
    templateUrl: "./app.component.html",
    styleUrls: ["./app.component.scss"],
})
export class AppComponent {
    showFloatingBanner: boolean = false
    
    constructor(
        private router: Router,
    ) {}

    ngOnInit() {
        this.getCurrentRoute()
    }

    getCurrentRoute() {
        this.router.events.subscribe(event => {
            if (event instanceof NavigationEnd) {
                let currentPage = this.router.url
                if (currentPage.indexOf('search') > -1 || currentPage.indexOf('gallery') > -1) {
                    this.showFloatingBanner = true
                } else {
                    this.showFloatingBanner = false
                }
            }
        })
    }
}
<div class="floating-banner hide" [ngClass]="{'show': showFloatingBanner}">
    ...more content here
</div>

scrollIntoView


Scroll to anchor from click on page or hash in url.

import { Router } from '@angular/router'

@Component({
    selector: "...",
    templateUrl: "...",
    styleUrls: ["..."],
})
export class HelpCenterComponent implements OnInit {
    constructor(
        private titleService: Title,
        private router: Router,
    ) { }

    ngOnInit() {
        // always scroll to url hash fragment, if any, after content is loaded
        setTimeout(() => {
            let urlHash = this.router.routerState.snapshot['url']
            let fragmentIdx = urlHash.lastIndexOf('#')
            let fragment = urlHash.substring(fragmentIdx + 1)
            if (fragment) {
                this.scrollOnPage(fragment)
            }
        }, 300)
    }

    public scrollOnPage(id: any) {
        let el = document.getElementById(id)
        if (!!el) {
            el.scrollIntoView()
        }
    }
}

<!-- Example of on click -->
<li>
    <a (click)='scrollOnPage("How-do-I-get-access-to-a-Tableau-item")'>How do I get access to a Tableau item?</a>
</li>

<!-- Example of ID to scroll to -->
<div id="How-do-I-get-access-to-a-Tableau-item">
    ...more content here
</div>
...

References


Be sure to unsubscribe from observables.