简体   繁体   中英

Change property of element <a> in angular 4

I bulid the folliwing nav.

<ul class="topnav">
        <li *ngFor="let menuItem of menuItems; let index = index">
          <a (click)='onClick($event)' [class.active]="index == 0" routerLink="{{ menuItem.link }}">{{ menuItem.name }}</a>
        </li>
      </ul>

At the start first in underlined.(css)

ul.topnav li a.active {
  border-bottom: 3px solid #27ae60;
}

I have added method onClick in element I defined this method in typescript file in class corresponding with this html with

onClick(someobject): void {
      someobject.target.attributes['class'].value = "active";
      console.log(someobject);
    }

However the class active does not apped to selected element. What is more how to clear mark class active from previous element?

Try the routerLinkActive directive. Option {exact:true} is needed if your route is also part of another route.

<a routerLink="dashboard" 
   routerLinkActive="active" 
   [routerLinkActiveOptions]="{exact:true}"
>Dashboard</a>

Ref: RouterLinkActive

Footnote
Add the directive to every anchor tag in the Nav, it will take care of adding and removing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM