Why is patchValue not functioning as expected? Is there another method that does the job

Encountering an issue with the image upload feature on a component form that consists of 8 entries - 7 text inputs and 1 image upload field. While all data is successfully submitted to the node server, the image upload function only sporadically works.

When attempting to choose an image, an error message pops up stating, "Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string."

<button class="btn logo" mat-stroked-button type="button"
   (click)="filePicker.click()">Pick Image
</button>
<input type="file" #filePicker formControlName="logo"
   name="logo" (change)="onImagePicked($event)" />

While I understand the error, similar syntax has been utilized in various examples. Is there an alternative approach that can be considered?

If modifications are made to 3 fields prior to selecting an image, the feature operates as intended by uploading the file via multer, adding the filename to the database, and returning results. However, the "failed to set value" error persists even though the functionality seems to work intermittently.

this.adminSettingsForm.patchValue({'logo': file,}); // doesn't work

this.adminSettingsForm.patchValue({['logo']: file,}); // doesn't work

this.adminSettingsForm.patchValue({[logo]: file,}); // doesn't work

this.adminSettingsForm.controls['logo'].patchValue(file, {emitEvent : false}); // doesn't work

this.adminSettingsForm.get('logo').updateValueAndValidity(); // throws an error because of the above.

The service responsible for sending and receiving data seems to function correctly, except for handling images.

updateStoreInfo(
storeName: string, logo: File, address: string,
city: string, state: string, zip: string, phone: string, email: string
) {
const formData = new FormData();
formData.append('storeName', storeName);
formData.append('logo', logo);
formData.append('address', address);
formData.append('city', city);
formData.append('state', state);
formData.append('zip', zip);
formData.append('phone', phone);
formData.append('email', email);

return this.http.post<{ message: string; settings: Settings }>(`${this.serverUrl}/admin/settings/storeInfo`, formData)
  .subscribe(result => {
    const resData = result;
    alert(resData['message']);
    const adminSettings = resData['settings'];
this.settingsChanged(adminSettings);
  });

}

Here's the corresponding functionality on the node server:

router.post('/settings/storeInfo', multer({dest: imgDir, storage: 
imgStorage, fileFilter: fileFilter})
  .fields([
    { name: 'logo', maxCount: 1 },
  ]), (req, res, next) => {


  storeSettingsId = req.body.storeSettingsId
  StoreSettings.findById(storeSettingsId)
    .then(settings => {
      if (req.files.logo) {
        settings.image= req.files.logo[0].filename;
      } else {
        settings.image = settings.image;
      }

      settings.storeName = req.body.storeName,
      settings.address = req.body.address,
      settings.city = req.body.city,
      settings.state = req.body.state,
      settings.zip = req.body.zip,
      settings.phone = req.body.phone,
      settings.email = req.body.email,
      settings.save();

      return res.status(201).json({ message: 'Settings Saved!', settings });
    })
    .catch(err => {
      console.log(err);
      const error = new Error(err);
      error.httpStatusCode = 500;
      return next(error);
    });

  });

Facing a persistent challenge while trying to submit forms with multiple image uploads. The last image tends to get overlooked during submission. After weeks of troubleshooting, seeking a fresh solution that hasn't already been Googled.

UPDATE: Code revisions have been implemented, yet issues persist: this.adminSettingsForm.patchValue({ 'logo': file }); // doesn't work - Failed to set the 'value' property... (console)

   this.adminSettingsForm.patchValue({'logo': file, });
// doesn't work with trailing comma - Failed to set the 'value' property... (console)

   this.adminSettingsForm.patchValue({['logo']: file, });
// doesn't work - Failed to set the 'value' property... (console)

   this.adminSettingsForm.patchValue({[logo]: file, });
// doesn't work - did I mean this.logo(IDE) - logo not defined(console)

   this.adminSettingsForm.controls['logo'].patchValue(file);
// refErr 'logo is not defined'

   this.adminSettingsForm.controls['logo'].patchValue(file, {emitEvent : false});
// dooesn't work - Failed to set the 'value' property... (console)

   this.adminSettingsForm.controls['logo'].value = file;
// Cannot assign to 'value' because it is a read-only property. Breaks build but not error in console

   this.adminSettingsForm.value['logo'].value = file; // doesn't work

All components appear to be functioning correctly apart from updating the file value entered. Seeking insights into this recurring issue as attempts at finding a resolution seem to lead back to square one.

Answer №1

Give it a shot:

this.userProfileForm.controls['photo'].value = picture;

or

this.userProfileForm.value['photo'].value = picture;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring Vue.js 3: Validating props with a custom type definition

I am currently working on a Vue.js 3 and Typescript single page application project. The issue I am facing involves a view and a single file component. In the People.vue component, data is fetched from the backend and displayed in multiple instances of th ...

Issue with web socket connections arising when attempting to add subscriptions within the URQL client

Seeking assistance in setting up subscriptions on URQL Client with Apollo server. I am facing difficulty getting the web socket to function properly on the client-side. Any guidance or support would be greatly appreciated. It seems like there may be an iss ...

Utilize a custom enum from a separate file to extend and redefine the i18next TFunction

I am attempting to customize the TFunction from the i18next package. The goal is to enforce typing on the i18n keys being used as follows: t('invalid-key') // should be invalid t('key1') // should be valid To achieve this, I created a ...

Retrieving desired route in Angular 2 RC5 within canDeactivate function

Is there a way to retrieve the desired route within the CanDeactivate guard of the Angular 2 RC5 router? I came across a solution for a similar scenario involving CanActivate (CanActivate), but it doesn't seem to apply to CanDeactivate. My specific s ...

TS - decorator relies on another irrespective of their position within the class

Is it possible to consistently run function decorator @A before @B, regardless of their position within the class? class Example { @A() public method1(): void { ... } @B() public method2(): void { ... } @A() public method3(): void { ... } } In the sc ...

Exploring Angular 4.3 Interceptors: A Practical Guide

I am currently working on a new app that needs authorization headers. Normally, I follow a similar approach to what is described in this article on scotch.io. However, I have recently learned that Angular 4 now fully supports HTTP Interceptors through the ...

Design a versatile dialog component using Angular to facilitate seamless communication within your

Creating reusable dialogs in Angular is a common requirement for many applications. These dialogs can vary in content, such as having a title, message, and buttons with different functions. Some dialogs may even include a dropdown menu. The challenge lies ...

Creating a cohesive "notification" feature in React with TypeScript that is integrated with one specific component

I am currently working on designing my application to streamline all notifications through a single "snackbar" style component (utilizing the material UI snackbar component) that encompasses the entire app: For instance class App extends React.Component ...

Angular and Node.js are powerful tools for creating HTTP clients

I have been facing an issue while trying to display event data from MongoDB in an Angular view. The data shows up fine in the browser console, but it does not appear on the website itself. I am using Node.js for the backend and Angular for the frontend wit ...

Incorporate a loading message for data retrieval within Fusion Chart on Angular 8

Is there a way to show a message before Fusion Chart loads data without using the render function on the component side? I have successfully created my charts with the following code: <fusioncharts width="100%" height="600" [type]="metric.type" [dataS ...

Switch the default blue color of Ngx-Pagination to a different color option

I am currently using the ngx-pagination plugin in my Angular 16 project and I would like to change the default blue color to a different one, is there anyone who can assist me with this? https://i.sstatic.net/NNuy7.png This is the HTML code snippet: < ...

Upgrading Angular from Version 9 to Version 10

Currently facing an issue while attempting to upgrade Angular from version 9 to 10. Despite manually updating the package.json file as below, I am encountering this error message: "@angular/core": "^10.2.5", "@angular/common": ...

The Angular JavaScript page successfully compiles, yet displays only a blank screen

I am facing an issue with my Angular app where it compiles successfully, but the HTML page appears blank and my application is not displaying properly. I have encountered similar problems in the past which were often related to Imports, but this time I&apo ...

Using Phoenix Channels and Sockets in an Angular 2 application: A comprehensive guide

My backend is built with Elixir / Phoenix and my frontend is built with Angular 2 (Typescript, Brunch.io for building, ES6). I'm eager to start using Phoenix Channels but I'm struggling to integrate the Phoenix Javascript Client into my frontend. ...

Angular form directive for managing arrays

export class TestComponent implements OnInit { models: Model[]; ngOnInit() { // numerous Observable pipes and subscriptions, one of which populates the models } add(): void { let newModel = {...}; this.models.push(ne ...

Can multiple parameters be passed in a routing URL within Angular 11?

app-routing.module.ts { path: 'projectmodel/:projectmodelname/salespack', component: componentname} When navigating using a button click, I want the URL to be structured in the following way: I attempted to achieve this by using the following co ...

Struggling to make Ionic 3 communicate with Angular using headers?

Currently utilizing Ionic 3 in conjunction with Angular 5.2.11. The trouble lies in Angular Post not functioning correctly when headers are involved .... const header = { "headers": { "X-Custom-Header": "1", ...

Reading the Ionic2 map object is a simple task within the Ionic2 framework. Let's delve

I am attempting to retrieve an object in ionic2 that contains key-value pairs, and I need to extract the key and the brand name from it using ionic2. My question is: How can I extract the key from the object below? { "status": "success", "produc ...

Having trouble figuring out how to display a tooltip using the show() method in @teamhive/ngx-tooltip?

I am looking for a way to toggle this tooltip on and off as I navigate with my mouse, especially because it is attached to nested elements. Although I can detect cursor movement for other purposes, I need a solution for controlling the tooltip display. Ac ...

Access functions and attributes in separate namespaces using a callback function

Incorporating the chartjs-plugin-annotation, I am faced with the need to trigger an event once a user clicks on an annotation to display a tooltip text. The plugin offers an event handler for the click event that allows me to retrieve the clicked element: ...