2017-02-18 200 views
5

我尝试使用[ngStyle]设置悬停属性状态。以下仅设置正常的状态颜色。当我将鼠标悬停在按钮上时,该按钮不会按预期方式更改为按下的颜色。Angular 2:使用ngStyle设置悬停属性

<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> 
+0

什么是'悬停'这里'[ngStyle] =“悬停{' ? –

+0

目前尚不清楚你想要什么。如果你想切换悬停样式,请将以下内容添加到按钮'

+0

我试图复制CSS .. .. .logout-container button:hover { } 希望为悬停状态设置按钮的颜色。我可以使用 .logout-container button:hover {颜色:#FFFFFF!important; background-color:rgba(0,0,0,0.00)!重要; border-color:#FFFFFF!important; } – user2182570

回答

0

:hover是伪类,它可以不使用style加入。您应该使用CSS和ngClass[class.xxxx]=".."

+0

你为什么认为他想设置':hover'?我想他想更改按钮悬停时的样式 –

+0

按钮有两种以上的状态:正常,悬停,聚焦,禁用,活动。 'ngStyle'最终会失败。 – kemsky

6

如果你想打开hover样式,添加以下按钮

<button (mouseover)="hover=true" (mouseleave)="hover=false"... 
1

如果您需要通过改变ngstyle选择各个按钮的,这是我做的。

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 
     }; 
    } 

}

希望这可以帮助别人:)