diff --git a/projects/common/element-components/directives/input-background-color.directive.ts b/projects/common/element-components/directives/input-background-color.directive.ts index eef0061c233bf7110ceab4c9af952f479ea5adc6..7bf48d945313945fac076a51b2f176517b990664 100644 --- a/projects/common/element-components/directives/input-background-color.directive.ts +++ b/projects/common/element-components/directives/input-background-color.directive.ts @@ -1,16 +1,19 @@ 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); } } }