Angular 2: set hover properties using ngStyle

I am trying to set the state of hover properties using [ngStyle]. The following sets only the colors of the normal state. When I click on the button, the button does not change to the pressed colors as expected.

<button (click)="logout()" class="btn register-button" [ngStyle]=" hover ? {'color': theme.logoutButtonColorPressed, 'border-color': theme.logoutButtonBorderColorPressed, 'background-color': theme.logoutButtonBackgroundColorPressed } : {'color': theme.logoutButtonColorNormal, 'border-color': theme.logoutButtonBorderColorNormal, 'background-color': theme.logoutButtonBackgroundColorNormal }">Logout</button> 
+5
source share
3 answers

If you want to switch styles on hover, add the following to the button

 <button (mouseover)="hover=true" (mouseleave)="hover=false"... 
+6
source

If you need to select individual buttons by changing ngstyle, this is what I did.

btn.component.html

 <div *ngIf="socketData && socketData.status === 'ok'"> <div *ngFor="let button of socketData.message; let i = index" [ngStyle]="hovered === i ? pressedStyle(button) : buttonStyle(button)" (mouseover)="hovered = i" (mouseout)="hovered = -1" (click)="reqTicket(button.id)"> {{button.someImportantData}} - {{button.yetMoreImportantData}} </div> </div> 

btn.component.ts

 export class ButtonComponent implements OnInit { style; hovered; ... private buttonStyle(button) { let btnType = this.setBtnType(button); this.style = { 'color': '#' + button.textColor, 'font-size': button.textSize + 'px', 'background-color': btnType.background }; return this.style; } private pressedStyle(button) { let pressed = this.setBtnType(button, this.hovered); this.style['background-color'] = pressed.background; return this.style; } private setBtnType(button, hovered?) { let type = 'normal'; let btn = { normal: { background: '#' + button.backColor, }, pressed: { background: '#' + button.backColor, } } if(hovered > -1) type = 'pressed'; return { border: btn[type].width + ' ' + btn[type].color + ' ' + 'solid', background: btn[type].background }; } 

}

Hope this helps someone :)

+1
source

:hover is a pseudo-class; it cannot be added using style . You must use CSS and ngClass or [class.xxxx]=".." .

0
source

Source: https://habr.com/ru/post/1264395/


All Articles