From 5050da99363dfca96b5714aaf3f681c90d2b9a48 Mon Sep 17 00:00:00 2001 From: Gabriel De Los Rios Date: Sun, 22 Feb 2026 20:04:46 -0300 Subject: [PATCH] feat: add directive for handling images in form --- src/app/directives/image-handler.spec.ts | 36 ++++++++++++++++++++++++ src/app/directives/image-handler.ts | 25 ++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 src/app/directives/image-handler.spec.ts create mode 100644 src/app/directives/image-handler.ts diff --git a/src/app/directives/image-handler.spec.ts b/src/app/directives/image-handler.spec.ts new file mode 100644 index 0000000..c709d5b --- /dev/null +++ b/src/app/directives/image-handler.spec.ts @@ -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: ` +
+
+
+ `, + styles: [], +}) +class ImageHandlerTestBed { + form = new FormGroup({ image: new FormControl(null) }); +} + +describe('ImageHandler', () => { + let component: ImageHandlerTestBed; + let fixture: ComponentFixture; + + beforeEach(async () => { + TestBed.configureTestingModule({ + imports: [ImageHandlerTestBed], + }).compileComponents(); + fixture = TestBed.createComponent(ImageHandlerTestBed); + component = fixture.componentInstance; + await fixture.whenStable(); + }); + + it('should create', () => { + expect(component).toBeTruthy(); + }); +}); diff --git a/src/app/directives/image-handler.ts b/src/app/directives/image-handler.ts new file mode 100644 index 0000000..37a5f73 --- /dev/null +++ b/src/app/directives/image-handler.ts @@ -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>(new FormControl(null)); + private readonly cd = inject(ChangeDetectorRef); + + ngOnInit() { + this.imageControl() + .valueChanges.pipe(take(1)) + .subscribe({ + next: () => this.cd.markForCheck(), + }); + } +}