简体   繁体   中英

Underline most recent clicked element

I am trying to find a way to keep track of the most recently clicked item and underline that item only. This is my current approach, however, it is underlining every item I have clicked on but not the most recent one. I also tried to use :active , :focus and :focus:active on li , but the underline doesn't stay.

In my HTML:

<li [ngClass]="{ 'target': isTarget }" (click)="updateTarget(t)"> 
  {{ details }} </li>

In my CSS:

li { 
  &.target {text-decoration: underline; } 
}

In my ts in angular 2:

updateTarget(t) {
   this.isTarget = t;
}

I am assuming your targets to be an array of json object. Here is how you can do it:

<li [ngClass]="{ 'target': isTarget === t  }" (click)="isTarget = t">
    {{details }} 
</li>

and your styles:

.target {
    text-decoration: underline;
}

Full code with example in this Plunker Demo

In your component, have an array, each member of which will correspond to an <li> in the view.

public target = null; // reference to the most recently clicked link
public links = [
  {details: '...'},
  {details: '...'},    
];

Then in your view, use *ngFor to iterate through links :

<li *ngFor="let link of links" [ngClass]="{'target': link===target }" 
    (click)="target = link">
    {{link.details}}
</li>

When user clicks a link, Angular will set the underlying object as the current target, and the ngClass directive will add the " target " class since link===target will be true only for the clicked link.

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