Skip to content Skip to sidebar Skip to footer

Angular 6: How To Highlight Element On Navbar Depending On Scroll?

I am making a single page in Angular 6. It a simple page and I would like to highlight navbar depending on scroll. here is my code: How can I highlight navbar element when I scrol

Solution 1:

Well it depends of how sophisticated your project is. In the very primitive way, you can do something like this:

Using ngClass, you are binding "active" class to currentActive variable.

<li><ahref="#" [ngClass]="{'active': currentActive === 1}">Home</a></li><li><ahref="#news" [ngClass]="{'active': currentActive === 2}" (click)="scrollToElement(new)">News</a></li><li><ahref="#contact" [ngClass]="{'active': currentActive === 3}" (click)="scrollToElement(con)">Contact</a></li><li><ahref="#about" [ngClass]="{'active': currentActive === 4}" (click)="scrollToElement(about)">About</a></li>

Now, about how to check our current scroll position (current YOffset). To get our current scroll position, and bind it to scroll event we can simply do this:

@HostListener('window:scroll', ['$event'])
checkOffsetTop() {
  console.log(window.pageYOffset); // this will console log our scroll position
}

Now what we would like, is to know at what Y positions are our anchors. To get this, we can use @ViewChild decorator.

@ViewChild('home') homeElement: ElementRef;
@ViewChild('con') conElement: ElementRef;
@ViewChild('new') newElement: ElementRef;
@ViewChild('about') aboutElement: ElementRef;

This only bind our references to our variables. To check their offsets, we would like to render our view first, so we will receive proper offsets. Because of that we will use ngAfterViewInit

ngAfterViewInit() {
  this.homeOffset = this.homeElement.nativeElement.offsetTop;
  this.conOffset = this.conElement.nativeElement.offsetTop;
  this.newOffset = this.newElement.nativeElement.offsetTop;
  this.aboutOffset = this.aboutElement.nativeElement.offsetTop;
}

Full code looks like this:

import { Component, AfterViewInit, ViewChild, ElementRef, HostListener } from'@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
exportclassAppComponent implements AfterViewInit {
  @ViewChild('home') homeElement: ElementRef;
  @ViewChild('con') conElement: ElementRef;
  @ViewChild('new') newElement: ElementRef;
  @ViewChild('about') aboutElement: ElementRef;

  public currentActive = 0;
  public homeOffset: Number = null;
  public conOffset: Number = null;
  public newOffset: Number = null;
  public aboutOffset: Number = null;

  ngAfterViewInit() {
    this.homeOffset = this.homeElement.nativeElement.offsetTop;
    this.conOffset = this.conElement.nativeElement.offsetTop;
    this.newOffset = this.newElement.nativeElement.offsetTop;
    this.aboutOffset = this.aboutElement.nativeElement.offsetTop;
  }

  scrollToElement() {
    // scrollToElement Code :)
  }

  @HostListener('window:scroll', ['$event'])
  checkOffsetTop() {
    if (window.pageYOffset >= this.homeOffset && window.pageYOffset < this.conOffset) {
      this.currentActive = 1;
    } elseif (window.pageYOffset >= this.conOffset && window.pageYOffset < this.newOffset) {
      this.currentActive = 2;
    } elseif (window.pageYOffset >= this.newOffset && window.pageYOffset < this.aboutOffset) {
      this.currentActive = 3;
    } elseif (window.pageYOffset >= this.aboutOffset) {
      this.currentActive = 4;
    } else {
      this.currentActive = 0;
    }
  }
}
.sticky {
    position: sticky;
    top: 0;
  }

  .active {
      font-weight: bold !important;
      color: red !important;
      font-size: 1.2rem!important;
  }

  #iul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: blue;
  }
  
  #ili {
    float: left;
  }
  
  #ilia {
    display: block;
    color: white;
    text-align: center;
    padding: 14px16px;
    text-decoration: none;
  }
  
  #ilia:hover {
    border-radius: 0px0px10px10px;
    background-color: rgb(43, 137, 226);
  }
  
  /* #i {
    margin: 0px 0px 40px 0px;
  } */#footer-id {
    background-color:blue;
  }
<spanid="i"><ulclass="sticky"><li><ahref="#" [ngClass]="{'active': currentActive === 1}">Home</a></li><li><ahref="#news" [ngClass]="{'active': currentActive === 2}" (click)="scrollToElement(new)">News</a></li><li><ahref="#contact" [ngClass]="{'active': currentActive === 3}" (click)="scrollToElement(con)">Contact</a></li><li><ahref="#about" [ngClass]="{'active': currentActive === 4}" (click)="scrollToElement(about)">About</a></li><ulclass="nav navbar-nav pull-right"><liclass="nav"><ahref="#">Contact</a></li></ul><ulclass="nav navbar-nav pull-right"><liclass="nav"><ahref="#ta" (click)="scrollToElement(con)">Target: {{ currentActive }}</a></li></ul></ul></span><divclass="container"style="margin-bottom: 20px;"><div #home><br /><br /><h1>Home | offset: {{ homeOffset }}</h1><p>You contact us here. Thank for your greatness</p><p>
      Welcome to the Random Phrase and Idiom Generator. There will be times when
      you may need more than a random word for what you want to accomplish, and
      this free online tool can help. The use of this tool is quite simple. All
      you need to do is indicate the number of random phrases you'd like to be
      displayed, and then hit the "Generate Random Phrases" button. Once done,
      your chosen number of idioms will be displayed along with the meaning of
      the idiom.
    </p><p>
      Welcome to the Random Phrase and Idiom Generator. There will be times when
      you may need more than a random word for what you want to accomplish, and
      this free online tool can help. The use of this tool is quite simple. All
      you need to do is indicate the number of random phrases you'd like to be
      displayed, and then hit the "Generate Random Phrases" button. Once done,
      your chosen number of idioms will be displayed along with the meaning of
      the idiom.
    </p></div><div #con><br /><br /><h1>Contact</h1><p>You contact us here. Thank for your greatness</p><p>
      Idioms are a wonderful part of the English language that give it a lot of
      flavor. They force people to know more than the literal meaning of words.
      Idioms are commonly used phrases which have a meaning completely different
      than their literal meaning. This can be quite confusing to those who
      aren't familiar with the idiom and those who are studying English.
    </p><p>
      Idioms are a wonderful part of the English language that give it a lot of
      flavor. They force people to know more than the literal meaning of words.
      Idioms are commonly used phrases which have a meaning completely different
      than their literal meaning. This can be quite confusing to those who
      aren't familiar with the idiom and those who are studying English.
    </p></div><div #new><br /><br /><h1>News</h1><p>This are new from us</p><p>
      Using this tool can be excellent practice for students studying English as
      a second language because it gives the literal meaning of each phrase.
      This allows them to see the phrase and its meaning at the same time. While
      there are long idiom lists available online, trying to navigate through
      them all on a single page can be daunting. Being able to create the exact
      number of random idioms which best suits your learning needs is a
      advantage this tool has over standard phrase list. In this way, this tool
      provides an excellent way for those learning English to practice their
      knowledge of English idioms and to learn new ones in the process.
    </p><p>
      Using this tool can be excellent practice for students studying English as
      a second language because it gives the literal meaning of each phrase.
      This allows them to see the phrase and its meaning at the same time. While
      there are long idiom lists available online, trying to navigate through
      them all on a single page can be daunting. Being able to create the exact
      number of random idioms which best suits your learning needs is a
      advantage this tool has over standard phrase list. In this way, this tool
      provides an excellent way for those learning English to practice their
      knowledge of English idioms and to learn new ones in the process.
    </p></div><div #about><br /><br /><h1>About</h1><p>This are new from us</p><p>
      It can also be a wonderful way for writers to brainstorm and spur more
      creativity in their writing. The tool can be used to get writing ideas
      flowing forcing the writer to use more creativity than they would with a
      single random word. For example, the writer can use the generated phrase
      to create a new paragraph or story. Since the writer has no idea what will
      appear, or even if they will be familiar with the idiom, it forces the
      writer to use creativity to incorporate it into what they're writing.
    </p><p>
      It can also be a wonderful way for writers to brainstorm and spur more
      creativity in their writing. The tool can be used to get writing ideas
      flowing forcing the writer to use more creativity than they would with a
      single random word. For example, the writer can use the generated phrase
      to create a new paragraph or story. Since the writer has no idea what will
      appear, or even if they will be familiar with the idiom, it forces the
      writer to use creativity to incorporate it into what they're writing.
    </p></div></div><!-- Footer --><footerclass="page-footer font-small indigo"id="footer-id"><!-- Footer Links --><divclass="container text-center text-md-left"><!-- Grid row --><divclass="row"><!-- Grid column --><divclass="col-md-3 mx-auto"><!-- Links --><h5class="font-weight-bold text-uppercase mt-3 mb-4">Links</h5><ulclass="list-unstyled"><li><ahref="#!">Very long link 1</a></li><li><ahref="#!">Very long link 2</a></li><li><ahref="#!">Very long link 3</a></li><li><ahref="#!">Very long link 4</a></li></ul></div><!-- Grid column --><hrclass="clearfix w-100 d-md-none" /><!-- Grid column --><divclass="col-md-3 mx-auto"><!-- Links --><h5class="font-weight-bold text-uppercase mt-3 mb-4">Links</h5><ulclass="list-unstyled"><li><ahref="#!">Link 1</a></li><li><ahref="#!">Link 2</a></li><li><ahref="#!">Link 3</a></li><li><ahref="#!">Link 4</a></li></ul></div><!-- Grid column --><hrclass="clearfix w-100 d-md-none" /><!-- Grid column --><divclass="col-md-3 mx-auto"><!-- Links --><h5class="font-weight-bold text-uppercase mt-3 mb-4">Links</h5><ulclass="list-unstyled"><li><ahref="#!">Link 1</a></li><li><ahref="#!">Link 2</a></li><li><ahref="#!">Link 3</a></li><li><ahref="#!">Link 4</a></li></ul></div><!-- Grid column --><hrclass="clearfix w-100 d-md-none" /><!-- Grid column --><divclass="col-md-3 mx-auto"><!-- Links --><h5class="font-weight-bold text-uppercase mt-3 mb-4">Links</h5><ulclass="list-unstyled"><li><ahref="#!">Link 1</a></li><li><ahref="#!">Link 2</a></li><li><ahref="#!">Link 3</a></li><li><ahref="#!">Link 4</a></li></ul></div><!-- Grid column --></div><!-- Grid row --></div><!-- Footer Links --><!-- Copyright --><divclass="footer-copyright text-center py-3">
    © 2018 Copyright:
    <ahref="https://mdbootstrap.com/education/bootstrap/"> MDBootstrap.com</a></div><!-- Copyright --></footer>

And remember. This is very RAW solution to your problem. It all depends on how sophisticated your app/component is. Anyway i hope this will clear some things out.

Post a Comment for "Angular 6: How To Highlight Element On Navbar Depending On Scroll?"