Tips for preserving updates following modifications in Angular 5/6?

I'm currently working on enhancing the account information page by implementing a feature that allows users to edit and save their details, such as their name. However, I am encountering an issue where the old name persists after making changes. Below is the snippet of my code for reference:

<div >
    <mat-form-field class="simple-form-field-50" *ngIf="isEditEnable">
      <input matInput placeholder="Name" [(ngModel)]="name">
    </mat-form-field>
    <span *ngIf="!isEditEnable">Name : {{user?.givenName}} </span>
    <button style="border:0;" *ngIf="!isEditEnable" (click)="onEdit()"><span><mat-icon style="font-size:16px;" matSuffix>create</mat-icon></span></button>
    <button *ngIf="isEditEnable" mat-raised-button color="primary" (click)="onEdit()">Submit</button>
</div>

TS code:

export class ProfileComponent implements OnInit {
  user: User;

  constructor(
    private http: HttpClient,
    ) { }

  isEditEnable = false;

  ngOnInit() {
    this.http.get<User>('/api/user/details', {})
        .subscribe((user) =>  {
          this.user = user;
        });
  }
  onEdit() {
  this.isEditEnable = !this.isEditEnable;
  }
}

Code Ouput:

[1] (https://i.stack.imgur.com/8Rbzz.png)

Upon clicking on the edit button:

[2] (https://i.stack.imgur.com/J7qCr.png)

Despite submitting the changes, the old name remains unchanged:

[3] (https://i.stack.imgur.com/8Rbzz.png)

Answer №1

It seems like there is an issue with updating the name property of the user and ensuring that the user is updated in the database as well (you may need to create an endpoint for this).

<div >
    <mat-form-field class="simple-form-field-50" *ngIf="isEditEnable">
        <input matInput placeholder="Name" [(ngModel)]="name">
    </mat-form-field>
    <span *ngIf="!isEditEnable">Name : {{user?.givenName}} </span>
    <button style="border:0;" *ngIf="!isEditEnable" (click)="onEdit()">
        <span><mat-icon style="font-size:16px;" matSuffix>create</mat-icon></span>
    </button>
    <button *ngIf="isEditEnable" mat-raised-button color="primary" (click)="onEdit()">
        Submit
    </button>
</div>

export class ProfileComponent implements OnInit {
    user: User;
    name: string;

    constructor(
      private http: HttpClient,
    ) { }

    isEditEnable = false;

    ngOnInit() {
      this.http.get<User>('/api/user/details', {})
          .subscribe((user) =>  {
            this.user = user;
          });
    }

    // assume you have or will add an endpoint to handle user update
    updateUser(user) {
        this.http.put((`/api/user/${this.user.id}`, this.user))
    }

    onEdit() {
        if (this.isEditEnable && this.user.givenName !== this.name) {                
                // assign new name to the user
                this.user.givenName = this.name;
                // use api update the user in your database
                this.updateUser()
        }
        this.isEditEnable = !this.isEditEnable
    }
}

In the backend portion (assuming you are using node with express maybe?), you may have a file named users.js where you define a get endpoint as follows:

this.router.get('details', someFunctionThatGetsUser);

You will also need to add another one

this.router.put('/:id', functionToUpdateUserInDB);

and include a function in your user service that updates the user in the database.

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

Methods for invoking a JavaScript function from TypeScript within an Angular2 application

Hey there! I'm looking to execute a regular JavaScript function from a TypeScript file. Let's say I have a JavaScript file called test.js and it's been imported into the index.html of my application. Now, I want to invoke the test() functi ...

Use a pipe to show the content of the md-input

In my Angular 2 Material application, I have a form that includes a price input: <md-input [(ngModel)]="price" placeholder="Price"> </md-input>{{price|customCurrency}} This input field uses a custom version of the CurrencyPipe which you c ...

What is the best way to delete a particular CSS class using jquery?

My task is to remove the "btn" class from items that have an additional argument in their class name, such as: <input type="button" class="btn btn-mini btn-success email-user" id="emailid5" value="Email Tester"> I specifically need to only remove t ...

The hidden attribute of UIWebView and its interplay with JavaScript

In the webViewDidStartLoad method, I hide the webview. Then a request is made. In the webViewDidFinishLoad method, I use stringByEvaluatingJavaScriptFromString. Finally, the webview is shown again. However, when I run the app, I can still see how the Java ...

What is the reason that I have to submit my mapped function twice in order for the updated state to show after modifying the array content?

When I try to display an image for the current value in the array item, the image does not display when I submit my value. I have to submit twice to display the value. Additionally, when changing the value and pressing submit, the content in the div does ...

When transitioning from another page, the header will cover a portion of the section

I am facing a specific issue that I need help with. My goal is to have the navigation bar link to different sections of a single page when clicked. For example, clicking on "Contact" should take the user to the contact section, and then if they click on "A ...

What could be causing the issue with this function not loading correctly the first time in Node.JS?

I am currently in the process of developing a Twitter bot using Node.JS. One issue I am facing is with a function that utilizes an npm library called "scrapejs" to extract data from Yahoo Finance. The problem arises when this function loads after the initi ...

JavaScript array loading failed for the C# web service

I am encountering an issue with a JavaScript object in my application that contains an array object, which is a collection of objects with two properties (Name, Value) on the server-side. Despite my efforts, when the code reaches the C# web service, the C ...

Using a numeral within a Font Awesome icon symbol to customize a label for a Google Maps marker

I have a Google Maps marker displayed below, applying a Font Awesome icon as the label/icon. However, I am unsure how to a.) change the color of the marker and b.) include a number inside the marker. Referencing this Stack Overflow post This is the code ...

The ngx-datatable encountered a resolution issue with its dependency tree and was unable to resolve it

I've been trying to incorporate ngx-datatables into an Angular 12 project by running the command npm install @swimlane/ngx-datatable. However, after installation, I encountered the following Errors: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to r ...

Unable to add ngRoute dependency in Angular

I'm facing an issue while trying to set up a basic Angular route in my current project, encountering the error: Uncaught Error: [$injector:modulerr] I have ensured that I have injected ngRoute as a dependency in my module and included the angular-rou ...

Fetching JSON data from a Node.js server and displaying it in an Angular 6 application

Here is the code snippet from my app.js: app.get('/post', (req,res) =>{ let data = [{ userId: 10, id: 98, title: 'laboriosam dolor voluptates', body: 'doloremque ex facilis sit sint culpa{ userId: 10' ...

The content of the served HTML Table remains static and requires a server restart for any updates to

Having been encountering this issue for quite some time, I have searched extensively for a solution but to no avail. Therefore, I am taking matters into my own hands and posing the question myself. The dilemma is as follows: https://i.stack.imgur.com/UZrQ ...

What causes the removeChild function to exhibit distinct behaviors when it comes to list items versus i tags?

It has come to my attention that the removeChild function does not behave in the same way with all elements, particularly when dealing with list items. I am currently using the i tag for icons from frontAwesome and would like to individually remove these i ...

Implementing multiple perspectives on a single webpage by keeping track of the browsing history with AngularJS and leveraging the

Within my AngularJS application, I have an about page that contains various sub-sections, all within the same template. My goal is to have each section accessible through its own unique URL that will automatically scroll down to the corresponding section i ...

Breaking up an array into smaller chunks with a slight twist

Here's a straightforward question. I have an array, like this: let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], maxChunkLength = 3; I am looking to divide this array into multiple arrays as follows: [[1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 9], [9, ...

Ways to reduce the size of images within a bootstrap carousel

I'm currently working on creating a carousel that will serve as a background image cover for my website, similar to the revolutionary slider in WordPress but without using a plugin. I am developing it specifically for my static website. The challenge ...

Managing errors in jQuery's .ajax function

Having some issues with jQuery.ajax() while trying to fetch an html code snippet from table_snippet.html and replacing the element in my html code. The error handler in jQuery.ajax() gets triggered instead of the expected success handler. <!DOCTYPE H ...

Tips for utilizing and incorporating an icon into a specific cell within ag-grid to signify that the cell can be edited

I am currently integrating ag-grid with angular 6. There is a specific column that needs to have editable cells. You can refer to the image below for better clarity. Is there a way to include an icon that, once clicked, allows the cell to become editable? ...

Cannot retrieve the <li> element from the array

I am trying to display list items inside an ordered list (ul) from an array, but I am facing issues with it. Whenever I try to map through the array, I encounter an error message saying Map is not a function. Any assistance on resolving this would be hig ...