У меня есть эта кнопка:
<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;
}
}
}
Цвет фона кнопки меняется, но я также хочу изменить цвет текста на кнопке при наведении курсора, в противном случае установите цвет по умолчанию.
Любое решение, спасибо.
вы можете использовать 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% близки к ответу.
Из того, что я исправляю:
Вы упускаете btnhovertxtcolor
Input()
недвижимость.
Когда срабатывает событие ввода мыши, вы устанавливаете цвет this.btncolor = '#28e979'
по умолчанию. Вы можете заменить значение на this.btnhovertxtcolor
. В остальном установите цвет кнопки (шрифта) белый или предпочитаемый вами цвет текста (при наведении).
Когда срабатывает событие отпускания мыши, по умолчанию цвет кнопки (шрифта) черный. Таким образом, вы можете установить его как черный или вам может потребоваться определить свой собственный цвет по умолчанию.
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';
}
}
}
Я бы сделал что-нибудь в этом духе... В моем случае я прикрепляю класс к элементу, но в вашем случае вы можете прикрепить цвет фона и цвет текста.
@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);
}
}