import {
Component,
OnInit,
ChangeDetectorRef
} from '@angular/core';
import {
FormGroup,
FormBuilder,
Validators
} from '@angular/forms';
export class TodoFormComponent {
todoForm: FormGroup = this.fb.group({
todo: ['', Validators.required],
image: ['', Validators.required], //making the image required here
done: [false]
})
constructor(
private fb: FormBuilder,
private cd: ChangeDetectorRef
) {}
/**
*@param event {EventObject} - the javascript change event
*@param field {String} - the form field control name
*/
onFileChange(event, field) {
if (event.target.files && event.target.files.length) {
const [file] = event.target.files;
// just checking if it is an image, ignore if you want
if (!file.type.startsWith('image')) {
this.todoForm.get(field).setErrors({
required: true
});
this.cd.markForCheck();
} else {
// unlike most tutorials, i am using the actual Blob/file object instead of the data-url
this.todoForm.patchValue({
[field]: file
});
// need to run CD since file load runs outside of zone
this.cd.markForCheck();
}
}
onSubmit() {
const formData = new FormData();
Object.entries(this.todoForm.value).forEach(
([key, value]: any[]) => {
formData.set(key, value);
}
//submit the form using formData
// if you are using nodejs use something like multer
)
}
}
<form [formGroup]="todoForm" (ngSubmit)="onSubmit()">
<input type="file" formControlName="image" (onchange)="onFileChange($event, 'image')"/>
<textarea formControlName="todo"></textarea>
<button type="submit">Submit</button>
</form>