Home > database >  How to access the background color of a button in a directive?
How to access the background color of a button in a directive?

Time:10-27

I need to access the background color of a button in order to change the text color depending if it's bright or dark. I need to access it in a directive.

If I try to get it this way:

this.el.nativeElement.backgroundColor

The console log in ngAfterViewInit shows undefined.

or this way:

this.el.nativeElement.style.backgroundColor

The console in ngAfterViewInit shows nothing.

Here is the button which uses the textHighlight directive:

<button type="submit"  textHighlight>
  {{ 'login.logIn' | translate }}
</button>

Here is the directive's code:

import { AfterViewInit, Directive, ElementRef, OnChanges, Renderer2, SimpleChanges } from '@angular/core';

@Directive({
  selector: '[textHighlight]'
})
export class TextHighlight implements AfterViewInit, OnChanges{

  color: string = '';

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


  ngOnChanges(changes: SimpleChanges): void {
    console.log('changes');
    console.log(this.el.nativeElement.style.backgroundColor);
  }

  ngAfterViewInit(): void {
    console.log('after');
    console.log(this.el.nativeElement.style.backgroundColor);
    console.log(this.el.nativeElement.backgroundColor);
  }

So, what am I doing wrong?

I've tried to add an @Input(), but it does not fit the requirements. Same with the viewChild, it is not what I'm looking for.

CodePudding user response:

Since html element is using a class not style, the directive can only detect the className

console.log(this.el.nativeElement.style.className);

You can either add a style tag in the element OR add a corresponding CSS classes to background colors and use if else condition to perform tasks based on the class name

  • Related