refactor(form-control): improve structure and formatting of component

This commit is contained in:
Lorenz Hilpert
2025-05-22 19:24:55 +02:00
parent 7c9839d93a
commit 0a4eb9bb1c

View File

@@ -3,11 +3,11 @@ import {
ChangeDetectionStrategy,
Input,
ContentChild,
ElementRef,
ViewEncapsulation,
ChangeDetectorRef,
OnDestroy,
AfterContentInit,
inject,
} from '@angular/core';
import { NgControl } from '@angular/forms';
import { EmptyControl } from './empty-control';
@@ -22,7 +22,7 @@ import { BooleanInput, coerceBooleanProperty } from '@angular/cdk/coercion';
styleUrls: ['form-control.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
host: { class: 'shared-form-control' },
host: { 'class': 'shared-form-control', '[attr.label]': 'label' },
imports: [FirstErrorPipe],
})
export class FormControlComponent implements OnDestroy, AfterContentInit {
@@ -32,6 +32,8 @@ export class FormControlComponent implements OnDestroy, AfterContentInit {
@ContentChild(NgControl, { static: true })
controlDirective: NgControl;
private _cdr = inject(ChangeDetectorRef);
get control() {
return this.controlDirective.control;
}
@@ -39,7 +41,10 @@ export class FormControlComponent implements OnDestroy, AfterContentInit {
required = false;
get displayLabel() {
return (this.label ?? this.control?.['name'] ?? '') + (this.required && this._hasRequiredMark ? '*' : '');
return (
(this.label ?? this.control?.['name'] ?? '') +
(this.required && this._hasRequiredMark ? '*' : '')
);
}
private _onDestroy$ = new Subject<void>();
@@ -50,17 +55,14 @@ export class FormControlComponent implements OnDestroy, AfterContentInit {
this._hasRequiredMark = coerceBooleanProperty(value);
}
constructor(
private _elementRef: ElementRef,
private _cdr: ChangeDetectorRef,
) {}
ngAfterContentInit() {
this.checkValidator();
this.control.statusChanges.pipe(takeUntil(this._onDestroy$)).subscribe(() => {
this.checkValidator();
this._cdr.markForCheck();
});
this.control.statusChanges
.pipe(takeUntil(this._onDestroy$))
.subscribe(() => {
this.checkValidator();
this._cdr.markForCheck();
});
}
ngOnDestroy() {
@@ -73,6 +75,4 @@ export class FormControlComponent implements OnDestroy, AfterContentInit {
this.required = !!errors?.required;
}
clickLabel() {}
}