libs/core-forms/src/lib/file-uploader-component-plugin/file-uploader.component.ts
DfCustomComponent<FileUploaderConfig>
| changeDetection | ChangeDetectionStrategy.OnPush |
| selector | df-file-uploader-component |
| standalone | true |
| imports | |
| styleUrls | ./file-uploader.component.scss |
| templateUrl | ./file-uploader.component.html |
| styleUrl | ./file-uploader.component.scss |
No results matching.
Properties |
Inputs |
Outputs |
constructor()
|
| config | |
Type : C
|
|
| Required : true | |
|
Inherited from
DfBaseComponent
|
|
|
The configuration object for this formfield. Note that derived formfield components should extend the |
|
| control | |
Type : AbstractControl
|
|
Default value : new UntypedFormControl()
|
|
|
Inherited from
DfBaseComponent
|
|
|
The If an existing If no If a form component doesn't use the Note that if |
|
| formAclPath | |
Type : string
|
|
|
Inherited from
DfBaseComponent
|
|
| isAclHandled | |
Type : boolean
|
|
Default value : false
|
|
|
Inherited from
DfBaseComponent
|
|
| isRetailChannel | |
Type : boolean
|
|
|
Inherited from
DfBaseComponent
|
|
| validationConfigs | |
Type : ValidationConfig[] | undefined
|
|
|
Inherited from
DfBaseComponent
|
|
| formEvent | |
Type : DfEventPayload
|
|
|
Inherited from
DfBaseComponent
|
|
|
Emits when events associated to the form control happen. The emitted object contains the data necessary to uniquely identify the event (field id and event type). It also contains the event data. |
|
| componentOrControlInitFinished |
Type : unknown
|
Default value : new ReplaySubject<AbstractControl | undefined>(1)
|
|
Inherited from
DfBaseComponent
|
|
This ReplaySubject is provided to emit the control once it is initialized. |
| errorMessages |
Type : WritableSignal<Observable[]>
|
Default value : signal([])
|
|
Inherited from
DfBaseComponent
|
|
The resolved validation error messages for the current control state. |
| Readonly nxErrorAppearance |
Type : ErrorStyleType
|
Default value : inject(ERROR_DEFAULT_OPTIONS, { optional: true })?.appearance ||
(inject<CHANNEL>(CHANNEL_TOKEN) === CHANNEL.EXPERT ? 'text' : 'message')
|
|
Inherited from
DfBaseComponent
|
import { NxButtonModule } from '@allianz/ng-aquila/button';
import {
FileItem,
NxFileUploaderButtonDirective,
NxFileUploaderComponent,
NxFileUploaderModule
} from '@allianz/ng-aquila/file-uploader';
import { NxIconModule } from '@allianz/ng-aquila/icon';
import { NxMessageModule } from '@allianz/ng-aquila/message';
import { getNativeElement$ } from '@allianz/taly-acl/input-element-injector-directive';
import { TalyRuntimeLocalizationService, ValidationConfig } from '@allianz/taly-core';
import { DfBaseModule, DfCustomComponent } from '@allianz/taly-core/dynamic-form';
import { ValidationErrorsModule } from '@allianz/taly-core/ui';
import {
AfterViewInit,
ChangeDetectionStrategy,
Component,
computed,
effect,
ElementRef,
inject,
signal,
viewChild
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { StatusChangeEvent, TouchedChangeEvent } from '@angular/forms';
import { LocalizeFn } from '@angular/localize/init';
import {
ALLOWED_FILE_TYPE_MIME_MAP,
DEFAULT_MAX_FILE_COUNT,
FILE_UPLOADER_ERROR_TRANSLATION_KEYS,
FILE_UPLOADER_UI_TRANSLATION_KEYS,
MAX_FILE_COUNT,
type FileUploaderConfig
} from './file-uploader-config.model';
import { FileUploaderStateService } from './file-uploader-state.service';
import { FileValidationRule, validateFiles, ValidationResult } from './file-uploader.validators';
import { PfeBusinessService } from '@allianz/ngx-pfe';
declare let $localize: LocalizeFn;
@Component({
selector: 'df-file-uploader-component',
imports: [
DfBaseModule,
NxButtonModule,
NxFileUploaderModule,
NxIconModule,
ValidationErrorsModule,
NxMessageModule
],
templateUrl: './file-uploader.component.html',
styleUrl: './file-uploader.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class FileUploaderComponent
extends DfCustomComponent<FileUploaderConfig>
implements AfterViewInit
{
private uploaderRef = viewChild.required(NxFileUploaderComponent);
private buttonRef = viewChild.required(NxFileUploaderButtonDirective);
private elementRef = inject(ElementRef<HTMLElement>);
private talyRuntimeLocalizationService = inject(TalyRuntimeLocalizationService);
private fileUploaderStateService = inject(FileUploaderStateService);
private pfeBusinessService = inject(PfeBusinessService, { optional: true });
protected isTouched = signal(false);
protected isDisabled = signal(false);
protected selectedItems = signal<FileItem[]>([]);
protected restoreValue = signal<FileItem[] | undefined>(undefined);
protected validationErrors = signal<ValidationResult['errors']>([]);
protected showLimitMessage = signal(false);
protected acceptString = computed(() => {
const types = this.config().config?.allowedFileTypes || [];
const mimeTypes = types.map((ext) => ALLOWED_FILE_TYPE_MIME_MAP[ext]);
return [...new Set(mimeTypes)].join(',');
});
protected isAtFileLimit = computed(() => {
const max = this.config().config?.maxNumberOfFiles ?? DEFAULT_MAX_FILE_COUNT;
const limit = Math.min(max, MAX_FILE_COUNT);
return this.selectedItems().length >= limit;
});
protected defaultButtonLabel = computed(
() =>
this.talyRuntimeLocalizationService.getTranslation(
FILE_UPLOADER_UI_TRANSLATION_KEYS.addFileButtonLabel
)() || $localize`:@@file-uploader.button.add-file:Add File`
);
protected defaultCloseLabel = computed(
() =>
this.talyRuntimeLocalizationService.getTranslation(
FILE_UPLOADER_UI_TRANSLATION_KEYS.closeButtonLabel
)() || $localize`:@@file-uploader.button.close:Close`
);
protected maxFilesReachedLabel = computed(
() =>
this.talyRuntimeLocalizationService.getTranslation(
FILE_UPLOADER_UI_TRANSLATION_KEYS.maxFilesReachedLabel
)() || $localize`:@@file-uploader.error.max-files-reached:Maximum number of files reached.`
);
constructor() {
super();
this.enrichedValidationConfigs = computed(() => {
const backendError = this.fileUploaderStateService.backendError();
const configs = this.validationConfigs() ?? [];
if (!backendError) return configs;
return [
...configs,
{
validatorName: backendError,
errorMessage: this.getErrorMessage(backendError)
} as unknown as ValidationConfig
];
});
effect(() => {
const backendError = this.fileUploaderStateService.backendError();
const control = this.control();
if (!control) return;
if (backendError) {
control.setErrors({ ...control.errors, [backendError]: true });
} else {
control.updateValueAndValidity();
}
});
}
ngAfterViewInit(): void {
const id = this.config().id;
// Reset uploader state when the journey model clears this field's value.
this.pfeBusinessService
?.getObservableForExpressionKey(`$..['${id}']`, true)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((value) => {
if (value === null || value === undefined) {
this.selectedItems.set([]);
this.restoreValue.set([]);
this.fileUploaderStateService.clear(id);
this.control()?.setValue(null);
}
});
const control = this.control();
if (control) {
getNativeElement$(control).next(this.elementRef.nativeElement);
control.events.pipe(takeUntilDestroyed(this.destroyRef)).subscribe((event) => {
if (event instanceof TouchedChangeEvent) this.isTouched.set(event.touched);
if (event instanceof StatusChangeEvent) this.isDisabled.set(control.disabled);
});
}
// [accept] binding on nx-file-uploader triggers NDBX's own validation, duplicating our error messages.
const nativeInput = this.elementRef.nativeElement.querySelector('input[type="file"]');
nativeInput?.setAttribute('accept', this.acceptString());
const restoreItems = this.fileUploaderStateService.get(this.config().id);
if (restoreItems?.length) {
this.selectedItems.set(restoreItems);
this.restoreValue.set([...restoreItems]);
}
const onButtonClick = (event: MouseEvent) => {
if (this.isAtFileLimit()) {
this.showLimitMessage.set(true);
event.preventDefault();
event.stopPropagation();
}
};
const buttonElement = this.buttonRef().elementRef.nativeElement;
buttonElement.addEventListener('click', onButtonClick, true);
this.destroyRef.onDestroy(() =>
buttonElement.removeEventListener('click', onButtonClick, true)
);
}
protected dismissLimitMessage(): void {
this.showLimitMessage.set(false);
}
protected async handleFilesSelected(fileItems: FileItem[]): Promise<void> {
if (!fileItems?.length) return;
const existingItems = this.selectedItems();
const newItems = this.filterDuplicates(fileItems, existingItems);
if (!newItems.length) return;
const result = await this.validateNewFiles(existingItems, newItems);
this.removeInvalidFilesFromUploader(newItems, result.errors);
const validNewItems = this.extractValidItems(newItems, result.validFiles);
const updatedItems = [...existingItems, ...validNewItems];
// Without this, a stale 'uploadFailed' signal from a previous attempt would not change
// when the backend returns the same error again, preventing the effect from re-firing.
if (validNewItems.length) {
this.fileUploaderStateService.setBackendError(null);
}
this.applyState(updatedItems, result.errors);
}
private filterDuplicates(incoming: FileItem[], existing: FileItem[]): FileItem[] {
const existingSet = new Set(existing);
return incoming.filter((item) => !existingSet.has(item));
}
private async validateNewFiles(
existing: FileItem[],
incoming: FileItem[]
): Promise<ValidationResult> {
const toFiles = (items: FileItem[]) =>
items.map((item) => item.file).filter((file): file is File => file !== null);
return validateFiles(
toFiles(existing),
toFiles(incoming),
this.config().config ?? { allowedFileTypes: [] }
);
}
private removeInvalidFilesFromUploader(
newItems: FileItem[],
errors: ValidationResult['errors']
): void {
const invalidFiles = new Set(errors.flatMap((e) => e.files));
newItems
.filter((item) => item.file && invalidFiles.has(item.file))
.forEach((item) => {
if (this.uploaderRef().value?.some((val) => val.file === item.file)) {
this.uploaderRef().removeFile(item);
}
});
}
private extractValidItems(newItems: FileItem[], validFiles: File[]): FileItem[] {
const validSet = new Set(validFiles);
return newItems.filter((item) => item.file && validSet.has(item.file));
}
private applyState(updatedItems: FileItem[], errors: ValidationResult['errors']): void {
this.selectedItems.set(updatedItems);
this.validationErrors.set(errors);
this.showLimitMessage.set(false);
this.fileUploaderStateService.set(this.config().id, updatedItems);
this.control()?.setValue(
updatedItems.length
? updatedItems.map((item) => ({
name: item.name,
size: item.size,
type: item.file?.type ?? ''
}))
: null
);
this.control()?.markAsDirty();
this.control()?.markAsTouched();
}
protected removeValidationError(rule: FileValidationRule): void {
const updated = this.validationErrors().filter((error) => error.rule !== rule);
this.validationErrors.set(updated);
}
protected handleFileDeleted(deletedItem: FileItem): void {
const updatedItems = this.selectedItems().filter((item) => item !== deletedItem);
if (updatedItems.length === this.selectedItems().length) return;
this.fileUploaderStateService.setBackendError(null);
this.applyState(updatedItems, []);
}
protected getErrorMessage(rule: FileValidationRule): string {
const defaults: Record<FileValidationRule, string> = {
invalidExtension: $localize`:@@file-uploader.error.invalid-extension:These files cannot be uploaded because they have invalid file extensions.`,
exceedsCount: $localize`:@@file-uploader.error.exceeds-count:These files cannot be uploaded because the number of files exceeds the limit.`,
belowMinSize: $localize`:@@file-uploader.error.below-min-size:These files cannot be uploaded because they do not meet minimum file size requirement.`,
exceedsMaxFileSize: $localize`:@@file-uploader.error.exceeds-max-file-size:These files cannot be uploaded because they exceed the maximum allowed file size.`,
exceedsTotalSize: $localize`:@@file-uploader.error.exceeds-total-size:These files cannot be uploaded because the total size of all files exceeds the limit. (10 MB)`,
nameTooLong: $localize`:@@file-uploader.error.name-too-long:These files cannot be uploaded because their names exceed the length limit.`,
duplicate: $localize`:@@file-uploader.error.duplicate:These files cannot be uploaded because they are duplicates.`,
corrupted: $localize`:@@file-uploader.error.corrupted:Upload denied. The uploaded file is corrupted and cannot be processed.`,
uploadFailed: $localize`:@@file-uploader.error.upload-failed:Please upload a file with the correct file type to proceed.`
};
return (
this.talyRuntimeLocalizationService.getTranslation(
FILE_UPLOADER_ERROR_TRANSLATION_KEYS[rule]
)() || defaults[rule]
);
}
}
<nx-file-uploader
[id]="config().id"
[disabled]="isDisabled()"
[attr.data-testid]="config().testId"
[multiple]="true"
[noBlockingValidators]="true"
[value]="restoreValue()"
(filesSelected)="handleFilesSelected($event)"
(fileDeleted)="handleFileDeleted($event)"
>
<nx-label
[size]="isRetailChannel() ? 'large' : 'small'"
[ngClass]="{
'nx-font-weight-regular': isRetailChannel()
}"
class="nx-margin-bottom-3xs"
>{{ config().label | interpolateFromStore | async }}
</nx-label>
@if (config().config?.uploadHintText) {
<span class="nx-margin-bottom-s" nxFileUploadHint>{{
config().config?.uploadHintText | interpolateFromStore | async
}}</span>
}
<button nxButton="primary" type="button" class="nx-margin-bottom-s" nxFileUploadButton>
<nx-icon name="plus" class="nx-margin-right-2xs" aria-hidden="true"></nx-icon>
{{
(config().config?.addFileButtonLabel | interpolateFromStore | async) || defaultButtonLabel()
}}
</button>
</nx-file-uploader>
@if (isAtFileLimit() && showLimitMessage()) {
<nx-message
context="error"
class="nx-margin-top-xs"
[closable]="true"
(close)="dismissLimitMessage()"
[closeButtonLabel]="defaultCloseLabel()"
>
{{ maxFilesReachedLabel() }}
</nx-message>
} @if (isTouched() && !validationErrors().length) { @for (message$ of errorMessages(); track $index)
{
<nx-error class="nx-margin-top-xs" [appearance]="nxErrorAppearance">{{
message$ | async
}}</nx-error>
} }@for (error of validationErrors(); track error.rule) {
<nx-message
[context]="'error'"
[closable]="true"
(close)="removeValidationError(error.rule)"
[closeButtonLabel]="defaultCloseLabel()"
class="nx-margin-top-xs"
>
{{ getErrorMessage(error.rule) }}
<ul>
@for (file of error.files; track file.name) {
<li>{{ file.name }}</li>
}
</ul>
</nx-message>
}
./file-uploader.component.scss
ul {
margin-left: 24px;
}