'Update image in Angular 11
I have a task to develop a system that can update each employee's image in angular
form: FormGroup;
departments: FormGroup;
public fb: FormBuilder as instantiated in the constructor
this.form = this.fb.group({
companyName: [''],
companyAddress: [''],
department: this.fb.array([]),
})
createDepartment() {
this.departments = this.fb.group({
id: [''];
code: [''],
employees: this.fb.array([]),
});
}
get departmentControls() {
return (this.form.get(department) as FormArray).controls
}
export interface Department {
id: number;
code: string;
employees: Employee[];
}
export interface Employee {
id: number;
path: string;
name: string;
}
Here, imagePath is an s3 bucket URL
<div
formArrayName="department"
*ngFor="
let department of departmentControls;
let departmentIndex = index
"
>
<div [formGroupName]="departmentIndex">
// departmentIndex form group
<div
formArrayName="employee"
*ngFor="
let employee of department.get('employees').controls;
let employeeIndex = index
"
>
<div [formGroupName]="employeeIndex">
<input
type="file"
hidden
(change)="onUpdateHandler($event, department.value.id, employee.value.path)"
[id]="'department-image-input-' + employeeIndex"
/>
<img [src]="`${imagePath}${employee.value.path}?tr=w-200,h-200`" class="image-wrapper__img" />
<button
nbButton
status="warning"
(click)="onImageChangeClick(departmentIndex, employeeIndex)"
>
Change
</button>
</div>
</div>
</div>
</div>
I need to open a particular index file to update the image path below code is tried but excepted image is not changed
onImageChangeClick(departmentIndex: number, employeeIndex: number) {
// below code needs to change
const element = document.getElementById(`department-image-input-${employeeIndex}`) as HTMLInputElement;
element.click();
}
**for example, when 0 departmentIndex's department has 1 employee and 1 departmentIndex's the department has 1 employee when I click departmentIndex 1 employee's change button to
change image it change 0 departmentIndex's 0 employeeIndex employee image**
if departmentIndex 1 has 3 employees and departmentIndex 2 has 5 employees;
When I click departmentIndex 2 's employeeIndex 2 's image it changes departmentIndex=1 's employeeIndex 2's image
onUpdateHandler(event: Event, departmentId: number, path: string) {
const target = event.target as HTMLInputElement;
const file = target.files[0];
const data = new FormData();
data.append('file', file, file.name);
data.append('path', path);
// code for sent data to backend
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
