From 55e029c3e23f5cfe75dfb6987cbbf4b9fb50db7d Mon Sep 17 00:00:00 2001 From: rhenck <richard.henck@iqb.hu-berlin.de> Date: Wed, 29 Sep 2021 17:00:48 +0200 Subject: [PATCH] Improve background color directive The DOM query is now only done once and nt again everytime the value changes. --- .../directives/input-background-color.directive.ts | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) 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 eef0061c2..7bf48d945 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); } } } -- GitLab