如何在将鼠标悬停在div上时向div添加类.

模板-

<div class="red">On hover add class ".yellow"</div>

组成部分-

import {Component} from 'angular2/core';

@Component({
  selector: 'hello-world',
  templateUrl: 'src/hello_world.html',
  styles: [`
    .red {
      background: red;
    }

    .yellow {
      background: yellow;
    }

  `]
})
export class HelloWorld {
}

Demo

[注意-我特别想添加一个新类,而不是修改现有类]

叹息吧!这是一个很正常的用例,我还没有看到任何直接的解决方案!

推荐答案

您也可以使用以下内容:

[ngClass]="color" (mouseover)="changeStyle($event)" (mouseout)="changeStyle($event)"

然后在组件中

color:string = 'red';

changeStyle($event){
  this.color = $event.type == 'mouseover' ? 'yellow' : 'red';
}

Plunker

或者,执行标记中的所有操作:

[ngClass]="color" (mouseover)="color='yellow'" (mouseout)="color='red'"

Angular相关问答推荐

单元测试 case 模拟store 中的行为主体

try 测试具有Angular material 下拉列表的组件时,在Angular 17中发现&q;错误的意外合成属性@TransitionMessages

使选项卡与父零部件成一定Angular 激活

弯管记忆

角 12 固态继电器 |页眉页脚在加载程序到来之前显示

如何以Angular 显示动态视图模型

我想将一个对象传递给一个子组件.我做了一切,但没有任何效果. (Angular )

as和let之间的异步管道区别

异步管道模板中的局部变量(Angular 2+)

模块AppModule导入的意外指令LoginComponent,请添加@NgModule 注释

如何在 Angular2 中的所有请求的请求标头中发送Cookie?

ConnectionBackend 没有提供程序

Angular 2 组件不是任何 NgModule 的一部分

在Angular2 Dart中设置路由和RouterLink的正确方法是什么

无法在 RxJs 6 和 Angular 6 中使用 Observable.of

Angular单元测试输入值

RxJS - 发生错误时观察到的不会完成

包 '@angular/cli' 不是依赖项

升级到 angular-6.x 会给出Uncaught ReferenceError: global is not defined

如何使用 @ngrx/store 获取 State 对象的当前值?