Angular 2:使用ngStyle设置悬停属性

use*_*570 9 ng-style angular

我正在尝试使用[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>
Run Code Online (Sandbox Code Playgroud)

Max*_*kyi 10

如果要在悬停时切换样式,请将以下内容添加到按钮

<button (mouseover)="hover=true" (mouseleave)="hover=false"...
Run Code Online (Sandbox Code Playgroud)


kem*_*sky 5

:hover是一个伪类,不能使用style. 您应该使用 CSS 和ngClass[class.xxxx]="..".


Jos*_*ggs 5

如果您需要通过更改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>
Run Code Online (Sandbox Code Playgroud)

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
        };
    }
Run Code Online (Sandbox Code Playgroud)

}

希望这可以帮助某人:)