Skip to content
Snippets Groups Projects
Commit 55e029c3 authored by rhenck's avatar rhenck
Browse files

Improve background color directive

The DOM query is now only done once and nt again everytime the value 
changes.
parent 476e274a
No related branches found
No related tags found
No related merge requests found
import {
AfterViewInit,
Directive, ElementRef, Input, OnChanges
} from '@angular/core';
@Directive({
selector: '[appInputBackgroundColor]'
})
export class InputBackgroundColorDirective implements OnChanges {
export class InputBackgroundColorDirective implements AfterViewInit, OnChanges {
@Input() backgroundColor!: string;
private targetElements!: HTMLElement[];
constructor(private elementRef: ElementRef) { }
ngAfterViewInit(): void {
this.targetElements = this.elementRef.nativeElement.querySelector('div.mat-form-field-outline')?.children;
this.setBackgroundColor();
}
......@@ -19,11 +22,10 @@ export class InputBackgroundColorDirective implements OnChanges {
}
private setBackgroundColor(): void {
const targetElements = this.elementRef.nativeElement.querySelector('div.mat-form-field-outline')?.children;
// This fails, when component is not set up yet, therefore the extra check
if (targetElements) {
for (const child of targetElements) {
child.style.setProperty('background-color', this.backgroundColor);
if (this.targetElements) {
for (const element of this.targetElements) {
element.style.setProperty('background-color', this.backgroundColor);
}
}
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment