I am trying to set the hover property states using [ngStyle]
.
The following only sets the normal state colors. When I mouse over 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>
if you want to switch styles on hover, add the following to the button <button (mouseover)="hover=true" (mouseleave)="hover=false" ...
Combining NgStyle and NgClass Directives with our knowledge of Angular Template Syntax, we can marry conditional styling with Angular's Property & Event Binding.
The square brackets around the directive indicate that the NgStyle directive has an input property also called ngStyle. It is a common pattern to define the directive and bind to its input property at the same time. This is how we can pass our style information to the ngStyle directive.
If you want to switch styles on hover, add the following to the button
<button (mouseover)="hover=true" (mouseleave)="hover=false"...
If you are in need of selecting 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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With