Angular/Typescript - Change background color of a span when a link is clicked

旧巷老猫 提交于 2021-02-11 14:50:41

问题


I'm trying to change the color of a span when a link is clicked in order to indicate that it's checked. This must work in the form of a radio button, meaning that the color must disappear if another link is clicked (checked). I tried various methods using only html and css, but unfortunately I never managed to get it to work using :focus. At the moment, when I click on one of the filters there is no indication that one of the categories has been activated, heavily impacting the UX. I believe that this can be achieved using ngClass in angular, however, I'm really struggling to understand how this works. Any help would be really appreciated.

HTML:

<div class="checklist categories">
    <ul>
        <li><a data-action="filter-link" (click)="changeCategory(null)"><span></span>All</a></li>
        <li><a data-action="filter-link" (click)="changeCategory('House Favourites')"><span></span>House Favourites</a></li>
      </ul>
  </div>   

The styling of the span forms a small checkbox.


回答1:


u can use ngClass Demo

in css create your class and write which css you want

.active-link span{background-color:green;}

in html create ngClass for each list item

 <ul>
        <li><a data-action="filter-link" [ngClass]="{'active-link' : menus.allMenu}"  (click)="changeCategory(null,'allMenu')"><span></span>All</a></li>
        <li><a data-action="filter-link" [ngClass]="{'active-link' : menus.houseMenu}" (click)="changeCategory('House Favourites','houseMenu')"><span></span>House Favourites</a></li>
 </ul>

then in ts create model for menus

menus={allMenu:false,houseMenu:false}

with function first initialize it then change clicked one

changeCategory(el,event){
    this.menus.allMenu=false;
    this.menus.houseMenu=false;
    this.menus[event]=!this.menus[event];
  }


来源:https://stackoverflow.com/questions/62010493/angular-typescript-change-background-color-of-a-span-when-a-link-is-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!