Угловая директива – изменение цвета кнопки при наведении

У меня есть эта кнопка:

<button class = "btn-submit" type = "button" appControlhover 
  [defaultColor] = "btnBackgroundColor" 
  [highlightColor] = "btnhoverColor" 
  [btnhovertxtcolor] = "btnColor"
  style = "margin-top: 20px"                            
  (click) = "Submit()">      
    Send
</button>

тс код

btnBackgroundColor='#28e979';
btnhoverColor='#a6dabb';
btnhovertxtcolor='#848f90';

Пользовательская директива:

import { Directive, 
  OnInit, 
  Renderer2, 
  ElementRef, 
  HostListener,
  Input,
  OnChanges,SimpleChanges,
  HostBinding } from '@angular/core';

@Directive({
  selector: '[appControlhover]'
})
export class ControlhoverDirective implements OnChanges {

  @Input() defaultColor: string;
  @Input() highlightColor: string;
  @Input() isValid: boolean = true;
  @HostBinding('style.backgroundColor') backgroundColor: string;
  @HostBinding('style.color') btnhovercolor: string;

  constructor() { }
  ngOnInit() {

    if (this.highlightColor != 'none') {
      this.backgroundColor = this.defaultColor;
    } else if (this.highlightColor == 'none') {
        this.backgroundColor = this.defaultColor;
    } else {
      this.backgroundColor = this.defaultColor;
    }
  }

  @HostListener('mouseenter') mouseover(eventData: Event) {
    if (this.highlightColor != 'none') {
      this.backgroundColor = this.highlightColor;
      this.btncolor ='#28e979';
    } else if (this.highlightColor == 'none') {
      this.backgroundColor = this.defaultColor;
    } else {
      this.backgroundColor = this.defaultColor;
    }
  }

  @HostListener('mouseleave') mouseleave(eventData: Event) {

    if (this.highlightColor != 'none') {
      this.backgroundColor = this.defaultColor;
    } else if (this.highlightColor == 'none') {
      this.backgroundColor = this.defaultColor;
    } else {
      this.backgroundColor = this.defaultColor;
    }
  }
}

Цвет фона кнопки меняется, но я также хочу изменить цвет текста на кнопке при наведении курсора, в противном случае установите цвет по умолчанию.

Любое решение, спасибо.

Тестирование функциональных ngrx-эффектов в Angular 16 с помощью Jest
В системе управления состояниями ngrx, совместимой с Angular 16, появились функциональные эффекты. Это здорово и делает код определенно легче для...
Angular и React для вашего проекта веб-разработки?
Angular и React для вашего проекта веб-разработки?
Когда дело доходит до веб-разработки, выбор правильного front-end фреймворка имеет решающее значение. Angular и React - два самых популярных...
Эпизод 23/17: Twitter Space о будущем Angular, Tiny Conf
Эпизод 23/17: Twitter Space о будущем Angular, Tiny Conf
Мы провели Twitter Space, обсудив несколько проблем, связанных с последними дополнениями в Angular. Также прошла Angular Tiny Conf с 25 докладами.
Угловой продивер
Угловой продивер
Оригинал этой статьи на турецком языке. ChatGPT используется только для перевода на английский язык.
Мое недавнее углубление в Angular
Мое недавнее углубление в Angular
Недавно я провел некоторое время, изучая фреймворк Angular, и я хотел поделиться своим опытом со всеми вами. Как человек, который любит глубоко...
Освоение Observables и Subjects в Rxjs:
Освоение Observables и Subjects в Rxjs:
Давайте начнем с основ и постепенно перейдем к более продвинутым концепциям в RxJS в Angular
2
0
50
3
Перейти к ответу Данный вопрос помечен как решенный

Ответы 3

вы можете использовать https://angular.dev/api/core/Renderer2 и ссылку на элемент для доступа к текущему элементу и его DOM Renderer (чтобы изменить стиль).

export class ControlhoverDirective implements OnChanges {

  @Input() btnhovertxtcolor: string;
  defaulttxtcolor: string = '#fff'; // your default color here

  constructor(private el: ElementRef, private renderer: Renderer2) { }

  @HostListener('mouseenter') mouseover(eventData: Event) {
    this._setColor(this.btnhovertxtcolor);
  }

  @HostListener('mouseleave') mouseleave(eventData: Event) {
    this._setColor(this.defaulttxtcolor);
  }

  private _setColor(color: string) {
    this.renderer.setStyle(this.el.nativeElement, 'color', color);
  }
}
Ответ принят как подходящий

Судя по вашему коду, я думаю, что вы на 90% близки к ответу.

Из того, что я исправляю:

  1. Вы упускаете btnhovertxtcolorInput() недвижимость.

  2. Когда срабатывает событие ввода мыши, вы устанавливаете цвет this.btncolor = '#28e979' по умолчанию. Вы можете заменить значение на this.btnhovertxtcolor. В остальном установите цвет кнопки (шрифта) белый или предпочитаемый вами цвет текста (при наведении).

  3. Когда срабатывает событие отпускания мыши, по умолчанию цвет кнопки (шрифта) черный. Таким образом, вы можете установить его как черный или вам может потребоваться определить свой собственный цвет по умолчанию.

export class ControlhoverDirective implements OnChanges {
  @Input() defaultColor!: string;
  @Input() highlightColor!: string;
  @Input() isValid: boolean = true;
  @Input() btnhovertxtcolor!: string;
  @HostBinding('style.backgroundColor') backgroundColor!: string;
  //@HostBinding('style.color') btnhovercolor!: string;
  @HostBinding('style.color') btncolor!: string;

  constructor() {}

  ngOnChanges(changes: SimpleChanges): void {
    //throw new Error('Method not implemented.');
  }

  ngOnInit() {
    if (this.highlightColor != 'none') {
      this.backgroundColor = this.defaultColor;
    } else if (this.highlightColor == 'none') {
      this.backgroundColor = this.defaultColor;
    } else {
      this.backgroundColor = this.defaultColor;
    }
  }
  @HostListener('mouseenter') mouseover(eventData: Event) {
    if (this.highlightColor != 'none') {
      this.backgroundColor = this.highlightColor;
      //this.btncolor = '#28e979';
      this.btncolor = this.btnhovertxtcolor;
    } else if (this.highlightColor == 'none') {
      this.backgroundColor = this.defaultColor;
      this.btncolor = "white"
    } else {
      this.backgroundColor = this.defaultColor;
      this.btncolor = "white"
    }
  }

  @HostListener('mouseleave') mouseleave(eventData: Event) {
    if (this.highlightColor != 'none') {
      this.backgroundColor = this.defaultColor;
      this.btncolor = 'black';
    } else if (this.highlightColor == 'none') {
      this.backgroundColor = this.defaultColor;
      this.btncolor = 'black';
    } else {
      this.backgroundColor = this.defaultColor;
      this.btncolor = 'black';
    }
  }
}

Демо @ StackBlitz

Я бы сделал что-нибудь в этом духе... В моем случае я прикрепляю класс к элементу, но в вашем случае вы можете прикрепить цвет фона и цвет текста.

@Directive({
  // eslint-disable-next-line @angular-eslint/directive-selector
  selector: '[hoverClass]',
  standalone: true,
})
export class HoverClassDirective {
  elementRef = inject(ElementRef)
  @Input() hoverClass!: string;

  @HostListener('mouseenter')
  onMouseEnter() {
    this.elementRef.nativeElement.classList.add(this.hoverClass);
  }

  @HostListener('mouseleave') 
  onMouseLeave() {
    this.elementRef.nativeElement.classList.remove(this.hoverClass);
  }
}

Другие вопросы по теме