【问题标题】:Directive for changing the color of the card更改卡片颜色的指令
【发布时间】:2021-10-22 00:28:56
【问题描述】:

我有一个更改卡片颜色的指令

@Directive({
  selector: "[appColor]",
})
export class ColorDirective {
  @Input("color") color: string;
  constructor(private element: ElementRef, private render: Renderer2) {
    this.render.setStyle(this.element.nativeElement, "color", this.color);
    element.nativeElement.style.color = this.color;
  }

  @HostListener("mouseenter") onMouseEnter() {
    this.ChangeColor(this.color);
  }

  @HostListener("mouseleave") onMouseLeave() {
    this.ChangeColor("black");
  }

  ChangeColor(color: string) {
    this.render.setStyle(this.element.nativeElement, "color", color);
  }
}

我如何传递它,以便当我将鼠标悬停在卡片上时,卡片的颜色会根据它们的(卡片)类别而变化 卡片展示组件

          <div *ngIf="todos.length; else noTodos">
            <div routerLink="/todo/{{ todo.id }}" class="card" *ngFor="let todo of todos | filter:searchValue">
              <button class="btn btn-danger" (click)="deleteTodo(todo.id)">X</button>
              <div class="card-body">
                <h3 [class.completed]="todo.completed">{{todo.title | uppercase}}</h3>
                <p [class.completed]="todo.completed">{{todo.description}}</p>
              </div>
              <div>
                <div class="edit-button">
                  <div>Category: {{todo.category}}</div>
                  <div>
                    <button class="btn"><a routerLink="/todo/{{todo.id}}">Edit</a></button>
                    <button class="btn" (click)="completeTodo(todo.id)">Complete</button>
                  </div>
                </div>
              </div>
            </div>

          </div>

【问题讨论】:

    标签: angular angular-directive


    【解决方案1】:

    您可以将指令选择器添加到您想要的 html 组件中。

    这样

    <div appColor color="red"></div>
    

    这是一个完整的example 使用您的代码。

    【讨论】:

    • 我需要一点不同,我有一个卡片类别的枚举,每张卡片都有自己的类别,我需要将鼠标悬停在卡片上,例如使用 WORK 类别,卡片改变颜色等等和其他人
    • 好吧,您不需要为此指定指令,您只需将类别添加为类并根据 :hover 更改颜色
    • 这可能是真的,但指令是在任务中指定的
    • 哦,您可以在指令中传递类别,在指令中,根据类别更改颜色
    • 这是一个更新的堆栈,stackblitz.com/edit/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-24
    • 2021-07-05
    • 2020-08-19
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 2016-05-07
    相关资源
    最近更新 更多