简体   繁体   中英

How to change the css of the button on onclick in angular6?

I have few buttons in my webpage. I need to change the backgroundcolor & font-color when it is clicked. I have tried this,

<div class="card-body">
<h6 class="card-text">Data</h6>
<button ion-button block (click)="viewMore('data');
   displayPopup('data');" >
   ViewMore</button>&nbsp;
   <button ion-button block (click)="display('data');" >Display</button>
 </div> 

Likewise I have few more divs. Now I need to change the css of the viewmore button when it is clicked.

My css:

button:focus{
 background-color: blue;
}
button:active{
background-color: red;
} 

Now it is working for second button, when I click the first button popup comes & after closing the popup button css has not changed. Can somebody please suggest me?

The easiest way would be to use CSS pseudoclasses like you did. For clicked - or visited - elements, there's the :visited pseudoclass.

You should be familiar with basic css. W3schools is an awesome resource.

So in your case:

button:visited {
   background: red;
}

:focus is - as the same says - for the element which has focus.

Or:

button:active,
button:visited,
button:focus {
   background: red;
}

Your question it's not clear. The way to use ngStyle or ngClass otr style.attrib is used a variable and ternary operator. As you has severals buttons you need several variables. this variables can be a property of an object or an array. As an array

//You have an array
buttonsClicked:boolean[];
//In your .html

   <!--use index 0 for the first button, index 1 for the second button... -->
    <button ionbutton block [style.background-color]="buttonsClicked[0]?'red':'green'"
            (click)="buttonsClicked[0]=true;
                    viewMore('data');displayPopup('data');" >
       ViewMore</button>&nbsp;
       ....
     </div>

//when you close the popup you can clear all the buttonsClicked
this.buttonsClicked=[] //<--reinit the array

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