如何在Angular 6中单击更改div背景颜色

时间:2018-08-07 06:06:38

标签: angular angular6

下面是标记

<mat-card class="example-card" *ngFor="let filteredScreen of 
        filteredScreens"  let i = index >

      <mat-card-header>
          <div mat-card-avatar class="example-header-image" >
              <img mat-card-image class="list-img" src=" 
                {{filteredScreen?.img}}" >
          </div>
            <mat-card-content class="names" [innerHTML]="filteredScreen.name 
              | highlight: name"  >{{ 
                    filteredScreen?.name }}
           </mat-card-content>
      </mat-card-header>
    </mat-card>

如何更改

    <mat-card>

鼠标单击(不是将鼠标悬停)为任何颜色时的背景色,并且

     <mat-card-content> 

将颜色永久固定为任何颜色。我已经完成了鼠标悬停时更改背景颜色的操作,但是我想单击鼠标。

3 个答案:

答案 0 :(得分:1)

使用@HostListener

我已在 Stackblitz

上创建了一个演示
@HostListener('click') onMouseClick() {
    this.highlight(this.highlightColor || 'red');   
}

 private highlight(color: string) {
    this.el.nativeElement.style.backgroundColor = color;   
 }

答案 1 :(得分:1)

<mat-card [ngClass]="{'background-mad': x}" (click)="x = true">
<mat-card-content [ngClass]="{'color-mad': y}" (click)="y = true"> 

在ts文件中

public x: boolean = false;
public y: boolean = false;

在css文件中添加例如:

.background-mad {
    background-color: red
}
.color-mad {
    color: green
}

编辑
html:

<span [style.color]="color" (click)="changeColor()">aaaa</span>

ts:

private list: any = [
    'red',' green', 'blue'
];
  public color: 'black';
  changeColor() {
    this.color1 = this.list[Math.floor(Math.random() * this.list.length)];
  }

答案 2 :(得分:1)

指令是解决这类问题的好方法,例如可以像颜色一样进行配置,并且可以在该组件之外的其他组件上重用,而您无需在当前组件内部添加额外的逻辑。

import { Directive, HostBinding, Input,HostListener} from '@angular/core';
import { DomSanitizer, SafeStyle } from "@angular/platform-browser";

@Directive({
  selector: '[clickColor]'
})
export class ClickColorDirective {

  private toggle: boolean = false;
  @Input() color: string = 'red';

  constructor(private doms: DomSanitizer) { }

  @HostBinding('style') get myStyle(): SafeStyle {
    let style : string = this.toggle ? `background: ${this.color}` : '';
    return this.doms.bypassSecurityTrustStyle(style);
  }

  @HostListener('click') onClick() {
    this.toggle = !this.toggle;
  } 

}

模板

<div clickColor>
  Hello World from Angular
</div>

<div clickColor color='blue'>
   Angular  World
</div>

<div clickColor [color]="'#000'">
 Batman !!!
</div>

stackblitz example