Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ The versioning of material-addons is based on the Angular version. The Angular v
_Hint: Changes marked as **visible change** directly affect your application during version upgrade. **Breaking**
requires your attention during upgrade._

- **19.0.3**: Fix ReadonlyFormField/Wrapper: fix performance issues
- **19.0.2**: bugfix for version: fix dist output
- **19.0.0**: Upgrade to Angular 19
- **18.0.5**: FileUpload: Added additional param as 'removable' which allows user to remove file from fileList [#212](https://github.com/porscheinformatik/material-addons/pull/212)
Expand Down
2 changes: 1 addition & 1 deletion projects/material-addons/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@porscheinformatik/material-addons",
"version": "19.0.1",
"version": "19.0.3",
"description": "Custom theme and components for Angular Material",
"homepage": "https://github.com/porscheinformatik/material-addons",
"repository": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@

.alert .icon {
margin-right: 8px;
margin-top: 4px;
}

.alert .message {
Expand All @@ -35,7 +36,6 @@
.alert .close-btn {
color: inherit;
margin-left: auto;
padding: 0;
}

.alert .action-btn {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<div #contentWrapper [hidden]="readonly" (cdkObserveContent)="onContentChange()">
<div #contentWrapper [hidden]="readonly">
<ng-content></ng-content>
</div>

Expand All @@ -10,7 +10,6 @@
[textAlign]="textAlign"
[formatNumber]="formatNumber"
[decimalPlaces]="decimalPlaces"
[roundDisplayValue]="roundValue"
[autofillDecimals]="autofillDecimals"
[unit]="unit"
[unitPosition]="unitPosition"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { Component, DebugElement } from '@angular/core';
import { ReadOnlyFormFieldWrapperComponent } from './readonly-form-field-wrapper.component';
import { ReadOnlyFormFieldComponent } from '../readonly-form-field/readonly-form-field.component';
import { FormControl, FormGroup, FormGroupDirective, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { ReadOnlyFormFieldModule } from '../readonly-form-field.module';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInput } from '@angular/material/input';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';

@Component({
template: `
<form [formGroup]="form">
<mad-readonly-form-field-wrapper [readonly]="readonly" [value]="value">
<mat-form-field>
<mat-label>Test Label</mat-label>
<input formControlName="test" matInput />
</mat-form-field>
</mad-readonly-form-field-wrapper>
</form>
`,
standalone: true,
imports: [ReadOnlyFormFieldModule, MatFormFieldModule, FormsModule, ReactiveFormsModule, MatInput],
})
class WrapperTestHostComponent {
readonly = true;
value = 'Test Value';
form = new FormGroup({ test: new FormControl('Initial Value') });
}

describe('ReadOnlyFormFieldWrapperComponent', () => {
let fixture: ComponentFixture<WrapperTestHostComponent>;
let hostComponent: WrapperTestHostComponent;
let wrapperDebugEl: DebugElement;

beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [WrapperTestHostComponent, NoopAnimationsModule],
providers: [FormGroupDirective],
}).compileComponents();

fixture = TestBed.createComponent(WrapperTestHostComponent);
hostComponent = fixture.componentInstance;
wrapperDebugEl = fixture.debugElement;
fixture.detectChanges();
});

it('should create the host and wrapper component', () => {
expect(hostComponent).toBeTruthy();
const wrapper = wrapperDebugEl.query(By.directive(ReadOnlyFormFieldWrapperComponent));
expect(wrapper).toBeTruthy();
});

it('should render readonly component when readonly is true', () => {
const readonlyField = wrapperDebugEl.query(By.directive(ReadOnlyFormFieldComponent));
expect(readonlyField).toBeTruthy();
});

it('should render projected content when readonly is false', () => {
hostComponent.readonly = false;
fixture.detectChanges();
const input = wrapperDebugEl.query(By.css('input'));
expect(input).toBeTruthy();
expect(input.nativeElement.value).toBe('Initial Value');
});

it('should emit suffixClickedEmitter', () => {
const wrapperInstance = wrapperDebugEl.query(By.directive(ReadOnlyFormFieldWrapperComponent)).componentInstance;
jest.spyOn(wrapperInstance.suffixClickedEmitter, 'emit');
wrapperInstance.suffixClicked();
expect(wrapperInstance.suffixClickedEmitter.emit).toHaveBeenCalled();
});

it('should emit prefixClickedEmitter', () => {
const wrapperInstance = wrapperDebugEl.query(By.directive(ReadOnlyFormFieldWrapperComponent)).componentInstance;
jest.spyOn(wrapperInstance.prefixClickedEmitter, 'emit');
wrapperInstance.prefixClicked();
expect(wrapperInstance.prefixClickedEmitter.emit).toHaveBeenCalled();
});
});
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import {
AfterViewChecked,
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ElementRef,
EventEmitter,
Input,
OnChanges,
OnInit,
Output,
SimpleChanges,
ViewChild,
Expand All @@ -25,15 +24,16 @@ import { ObserversModule } from '@angular/cdk/observers';
@Component({
selector: 'mad-readonly-form-field-wrapper',
templateUrl: './readonly-form-field-wrapper.component.html',
styleUrls: ['./readonly-form-field-wrapper.component.css'],
styleUrls: ['./readonly-form-field-wrapper.component.scss'],
viewProviders: [{ provide: ControlContainer, useExisting: FormGroupDirective }],
imports: [NgIf, ReadOnlyFormFieldComponent, ObserversModule],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ReadOnlyFormFieldWrapperComponent implements OnInit, AfterViewInit, OnChanges, AfterViewChecked {
export class ReadOnlyFormFieldWrapperComponent implements AfterViewInit, OnChanges {
@ViewChild('contentWrapper', { static: false })
originalContent: ElementRef;
originalContent!: ElementRef;
@ViewChild('readOnlyContentWrapper', { static: false })
readOnlyContentWrapper: ElementRef;
readOnlyContentWrapper!: ElementRef;

/**
* If set to "false", the contained mat-form-field is rendered in all it's glory.
Expand All @@ -55,7 +55,7 @@ export class ReadOnlyFormFieldWrapperComponent implements OnInit, AfterViewInit,
@Input('unit') unit: string | null = null;
@Input('unitPosition') unitPosition: 'right' | 'left' = 'left';
@Input('errorMessage') errorMessage: string | null = null;
@Input() id: string;
@Input() id!: string;
Copy link

@LisaKirchhofer LisaKirchhofer Apr 28, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here and everywhere else: I think we should use

Suggested change
@Input() id!: string;
@Input({ required: true }) id: string;

instead :)

/**
* If set to "false", a readonly input will be rendered.
* If set to "true", a readonly textarea will be rendered instead.
Expand All @@ -65,7 +65,7 @@ export class ReadOnlyFormFieldWrapperComponent implements OnInit, AfterViewInit,
/**
* Defines the rows for the readonly textarea.
*/
@Input() rows: number;
@Input() rows!: number;

/**
* If shrinkIfEmpty is set to "false", nothing changes
Expand All @@ -74,15 +74,14 @@ export class ReadOnlyFormFieldWrapperComponent implements OnInit, AfterViewInit,
* Otherwise, the defined rows-value will be used
*/
@Input() shrinkIfEmpty = false;
@Input() hideIconInReadOnlyMode = false;
/**
* suffix iocon
*/
@Input() suffix: string;
@Input() suffix!: string;
/**
* prefix iocon
*/
@Input() prefix: string;
@Input() prefix!: string;
/**
* if cdkTextareaAutosize is active for textareas
*/
Expand All @@ -93,28 +92,27 @@ export class ReadOnlyFormFieldWrapperComponent implements OnInit, AfterViewInit,
/**
* Automatically taken from the contained <mat-label>
*/
label: string;
label!: string;
private initialized = false;

constructor(
private changeDetector: ChangeDetectorRef,
private rootFormGroup: FormGroupDirective,
) {}

ngOnInit(): void {
this.doRendering();
ngOnChanges(_: SimpleChanges): void {
if (this.initialized) {
this.syncView();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need this?

}
}

ngAfterViewInit(): void {
this.doRendering();
this.initialized = true;
this.syncView();
this.extractLabel();
this.extractValue();
}

ngAfterViewChecked(): void {}

ngOnChanges(_: SimpleChanges): void {
this.doRendering();
}

getLabel(): string {
if (!this.label) {
this.extractLabel();
Expand All @@ -130,26 +128,20 @@ export class ReadOnlyFormFieldWrapperComponent implements OnInit, AfterViewInit,
this.prefixClickedEmitter.emit(null);
}

onContentChange(): void {
this.extractLabel();
this.extractValue();
}

private doRendering(): void {
private syncView(): void {
if (!this.originalContent) {
return;
}
if (!this.readonly) {
this.correctWidth();
return;
this.applyFullWidthStyle();
} else {
this.changeDetector.detectChanges();
}

this.changeDetector.detectChanges();
}

private extractLabel(): void {
if (!this.originalContent || !this.originalContent.nativeElement) {
return null;
return;
}
const labelElement = this.originalContent.nativeElement.querySelector('mat-label');
this.label = labelElement ? labelElement.innerHTML : 'mat-label is missing!';
Expand All @@ -172,11 +164,11 @@ export class ReadOnlyFormFieldWrapperComponent implements OnInit, AfterViewInit,
return;
}
if (form && form.get(formControlName)) {
this.value = form.get(formControlName).getRawValue();
this.value = form.get(formControlName)?.getRawValue();
}
}

private correctWidth(): void {
private applyFullWidthStyle(): void {
const formField = this.originalContent.nativeElement.querySelector('mat-form-field');
if (formField) {
formField.setAttribute('style', 'width:100%');
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { ReadOnlyFormFieldComponent } from './readonly-form-field.component';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { NumberFormatService } from '../../numeric-field/number-format.service';
import { ChangeDetectorRef, ElementRef, Renderer2 } from '@angular/core';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { By } from '@angular/platform-browser';

describe('ReadOnlyFormFieldComponent', () => {
let component: ReadOnlyFormFieldComponent;
let fixture: ComponentFixture<ReadOnlyFormFieldComponent>;
let numberFormatService: NumberFormatService;

beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [ReadOnlyFormFieldComponent, NoopAnimationsModule],
providers: [
NumberFormatService,
Renderer2,
ChangeDetectorRef,
{ provide: ElementRef, useValue: new ElementRef(document.createElement('div')) },
],
}).compileComponents();

fixture = TestBed.createComponent(ReadOnlyFormFieldComponent);
component = fixture.componentInstance;
numberFormatService = TestBed.inject(NumberFormatService);
fixture.detectChanges();
});

it('should create', () => {
expect(component).toBeTruthy();
});

it('should fallback to dash if value is not set', () => {
component.value = undefined;
component.ngOnChanges({});
expect(component.value).toBe('-');
});

it('should format number if formatNumber is true', () => {
const spy = jest.spyOn(numberFormatService, 'format').mockReturnValue('1,234.00');
component.value = 1234;
component.formatNumber = true;
component.ngOnChanges({});
expect(spy).toHaveBeenCalled();
expect(component.value).toBe('1,234.00');
});

it('should emit suffixClickedEmitter when suffix icon is clicked', () => {
const spy = jest.spyOn(component.suffixClickedEmitter, 'emit');
component.suffix = 'info';
fixture.detectChanges();
const suffixIcon = fixture.debugElement.query(By.css('[data-cy="suffix-icon"]'));
suffixIcon.triggerEventHandler('click');
expect(spy).toHaveBeenCalled();
});

it('should emit prefixClickedEmitter when prefix icon is clicked', () => {
const spy = jest.spyOn(component.prefixClickedEmitter, 'emit');
component.prefix = 'info';
fixture.detectChanges();
const prefixIcon = fixture.debugElement.query(By.css('[data-cy="prefix-icon"]'));
prefixIcon.triggerEventHandler('click');
expect(spy).toHaveBeenCalled();
});

it('should compute tooltip text correctly for unit position right', () => {
component.value = 123;
component.unit = '%';
component.unitPosition = 'right';
const tooltip = component['calculateToolTipText']();
expect(tooltip).toBe('123 %');
});

it('should compute tooltip text correctly for unit position left', () => {
component.value = 123;
component.unit = '$';
component.unitPosition = 'left';
const tooltip = component['calculateToolTipText']();
expect(tooltip).toBe('$ 123');
});
});
Loading