feat: add directive for handling images in form

This commit is contained in:
2026-02-22 20:04:46 -03:00
parent d25b7cb49c
commit 5050da9936
2 changed files with 61 additions and 0 deletions

View File

@@ -0,0 +1,36 @@
import { Component } from '@angular/core';
import { ImageHandler } from './image-handler';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms';
@Component({
selector: 'app-image-handler-mock',
imports: [ImageHandler, ReactiveFormsModule],
template: `
<form [formGroup]="form">
<div appImageHandler [imageControl]="form.controls.image"></div>
</form>
`,
styles: [],
})
class ImageHandlerTestBed {
form = new FormGroup({ image: new FormControl(null) });
}
describe('ImageHandler', () => {
let component: ImageHandlerTestBed;
let fixture: ComponentFixture<ImageHandlerTestBed>;
beforeEach(async () => {
TestBed.configureTestingModule({
imports: [ImageHandlerTestBed],
}).compileComponents();
fixture = TestBed.createComponent(ImageHandlerTestBed);
component = fixture.componentInstance;
await fixture.whenStable();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,25 @@
import { ChangeDetectorRef, Directive, HostListener, inject, input, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { take } from 'rxjs';
//TODO: maybe this could be somehow integrated into the file input using ControlValueAccesor
@Directive({
selector: '[appImageHandler]',
})
export class ImageHandler implements OnInit {
@HostListener('file', ['$event' as any]) updateFileImage(file: File | null) {
const control = this.imageControl();
control.patchValue(file);
control.markAsDirty();
}
imageControl = input<FormControl<File | null>>(new FormControl(null));
private readonly cd = inject(ChangeDetectorRef);
ngOnInit() {
this.imageControl()
.valueChanges.pipe(take(1))
.subscribe({
next: () => this.cd.markForCheck(),
});
}
}