feat: add directive for handling images in form
This commit is contained in:
36
src/app/directives/image-handler.spec.ts
Normal file
36
src/app/directives/image-handler.spec.ts
Normal 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();
|
||||
});
|
||||
});
|
||||
25
src/app/directives/image-handler.ts
Normal file
25
src/app/directives/image-handler.ts
Normal 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(),
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user