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

Angular generates an array that is not native to the system

When I directly set vm.files in my view using the following code: <input type="file" ng-model= vm.files[0]> <input type="file" ng-model= vm.files[1]> The contents of vm.files are displayed as shown in example A: https://i.stack.imgur.com/K3V ...

Populate an HTML table using a JavaScript array containing objects

Greetings, fellow coders! I am new to the coding world and this community, and despite my efforts in searching for a solution, I couldn't find exactly what I was looking for. So, here is my question: I have an array structured as follows: const arr ...

Angular not firing slide.bs.carousel or slid.bs.carousel event for Bootstrap carousel

I've searched high and low with no success. I'm attempting to detect when the carousel transitions to a new slide, whether it's automatically or by user click. Despite my numerous attempts, I have been unable to make this event trigger. I ha ...

Determining the best method for change detection in Angular 2: Choosing between Observable, EventEmitter, and Dot Rule

Managing change detection in Angular2 can be approached in three different methods that I have observed. Utilizing Observables @Injectable() export class TodosService { todos$: Observable<Array<Todo>>; private _todosObserver: any; ...

When utilizing styled-jsx alongside postcss, experiencing issues with styles failing to reload or rebuild

I'm currently using postcss in conjunction with styled-jsx. In my setup, I have multiple CSS files that I'm importing using the @import directive within the _app.js file. Everything seems to work smoothly, except when I modify any of the CSS file ...

Execute a specific function when the Node.js countdown reaches zero

I am currently working on a web application and I need to incorporate a new function. This function will display a table containing certain results when a user submits a request. If the user does not submit anything, it will show different results as tim ...

transferring information from a nested input field in Vue to its parent component

I need to send the input data from a child component to the parent component's data property by using the $emit method. Directly binding the transmitted property to the child property using v-bind within the <input v-model="userinput" /&g ...

How can you prevent multiple instances of JavaScript objects from being disposed of after they have completed their task?

I'm facing an issue with the code snippet below: $(document).ready(function() { $('.container').ready(function() { var v = new Video($(this)); v.load(); }); }); I'm trying to prevent the object 'v&apos ...

Access Flask variable in JavaScript code

Currently working on a CTF challenge, my query is not seeking assistance in solving it, but rather pertains to syntax. The task involves retrieving the secret key from Flask server's configuration. This key is stored within the app.secret_key variable ...

What is the best way to ensure that the swf loads only after all the images and text have loaded completely

Is there a way to use jQuery to control the loading of SWF files on my CMS system? Sometimes when a video is included in the SWF file, it uses up bandwidth and makes the page non-responsive for a while. I would like the SWF files to load after the other co ...

Wondering how to go back to the default locale in Next.js?

Within my Next.js application, I have successfully implemented the next-i18next module for multi-language support. The app currently supports two languages: English and Arabic, with English set as the default. To allow users to toggle between languages, I ...

The issue with Angular's Mat Option selected values not functioning properly

We have a scenario where there are two form fields, and the second field needs to be disabled or enabled based on the selected value from the first field. The first field contains 5 values: 'a', 'b', 'c', 'd', ' ...

What is the best way to showcase information from an external API in react js?

As I develop my new app, I am integrating API data from . This feature will enable users to search for their favorite cocktail drinks and display the drink name fetched from the API on the page. However, I am encountering an error that says "Uncaught TypeE ...

Creating atomic controller actions in Sails.js: A guide to optimizing your controller functions

If I am looking to perform multiple operations within a Sails.js controller, how can I ensure that these actions are atomic to maintain the correctness of the results? This includes not only database operations but also various Javascript processing tasks. ...

Angular 2 is throwing an error: Unhandled Promise rejection because it cannot find a provider for AuthService. This error is occurring

My application utilizes an AuthService and an AuthGuard to manage user authentication and route guarding. The AuthService is used in both the AuthGuard and a LoginComponent, while the AuthGuard guards routes using CanActivate. However, upon running the app ...

Access a different tab through the utilization of JavaScript functions

Hi everyone, I recently created tabs using bootstrap, but I am facing a challenge with a specific scenario. I need the active tab to switch to another tab when a submit button is clicked. <div id="checkout-progress"> <ul class="nav nav-tabs"& ...

Transforming react.js into HTML and CSS programming languages

I have a small experiment I need help with. As I am not familiar with react.js, I would like to convert my main.jsx file into pure HTML/CSS/JS without using react. The issue I'm facing is how to handle form data submission to the server in vanilla HTM ...

Creating multi-dimensional arrays using array lists with Axios and Vue.js

My knowledge of axios and JavaScript is limited, and I find myself struggling with creating a multi-dimensional array. 1. This is how I want my data to be structured : https://i.stack.imgur.com/kboNU.png userList: [ { ...

What is the best way to make a Modal triggered by a loop embedded within a table function properly on mobile devices?

While the modal is functioning properly on desktop, it seems to be encountering issues on mobile devices. The modal appears behind the background and is confined by the boundaries of the table (tbody). Below is the code snippet for triggering the modal: ...

Extracting data from a JSON object using Angular

Recently, I've been delving into the world of AngularJS and encountered a hurdle with LocalStorage. After spending numerous hours trying to figure out how to save data locally, I believe I have finally got it working as intended. Now, my next challeng ...