Angular Dialog "Popup" for Updating Information

Currently, I am in the process of developing a "config" page where users can add objects/devices. When a user adds an object, it opens a Dialog window displaying the properties/fields of that particular object. The window includes Save and Cancel buttons. Upon hitting Save, the object is added to an array/list and all added objects are displayed. Each array item has an edit button which opens the same dialog window for editing purposes.

My challenge lies in enabling users to edit data without making real-time changes to the list object until they hit the "save" button. To address this issue, I want to pass the entire object as a copy back and forth rather than just a single property like the object's name.

While adding items to the list poses no problem, editing them has proven to be more challenging. It's worth mentioning that I'm relatively new to Angular and JavaScript/Typescript, although I do have some experience with Object-Oriented Programming (OOP).

I've managed to make this work effectively by passing a single property, as shown in the first block of code below:

//This works as RoomGroup only has a name property.
export class RoomGroupDialogComponent implements OnInit {

  tempGroup: ConfigRoomGroup;
  newGroup = true;

  constructor(public diaglogRef: MatDialogRef<RoomGroupDialogComponent>,
              @Inject(MAT_DIALOG_DATA) private group: ConfigRoomGroup,
              public config: ConfigService) { }

  ngOnInit() {
    if (this.group.name) {
      this.newGroup = false;
    } else {
      this.newGroup = true;
      this.group.name = 'New Group';
    }
    this.tempGroup = Object.assign({}, this.group);


  }
  onSaveClick(): void {

    if (this.newGroup) {
      this.config.configData.roomSetup.groups.push(this.tempGroup);
    } else {
      this.group.name = this.tempGroup.name;
      console.log(this.group);
    }

    this.diaglogRef.close();
  }

  onCancelClick(): void {
    this.diaglogRef.close();
  }

}
///This does not work
export class RoomDialogComponent implements OnInit {

  tempRoom: ConfigRoom;
  newRoom = true;

  constructor(public dialogRef: MatDialogRef<RoomDialogComponent>,
              @Inject(MAT_DIALOG_DATA) private room: ConfigRoom,
              public config: ConfigService) { }

  ngOnInit() {
    if ( this.room.name) {
      this.newRoom = false;
    } else {
      this.newRoom = true;
      this.room.name = 'New Room';
    }

    this.tempRoom = Object.assign({}, this.room);
  }

  onSaveClick(): void {
    if (this.newRoom) {
      console.log(this.tempRoom);
      this.config.configData.roomSetup.rooms.push(this.tempRoom);
    } else {
      this.room = this.tempRoom;
      console.log(this.tempRoom);
      console.log(this.room);
      console.log(this.config.configData.roomSetup.rooms);
    }

    this.dialogRef.close();
  }

  onCancelClick(): void {
    this.dialogRef.close();
  }
}

Answer №1

In the realm of Javascript, a prevalent issue arises due to objects being passed by reference rather than by value. As a result, when room and group properties are passed into constructors, they become pointers to objects instead of the actual objects themselves. Manipulating the value of an object's property directly impacts the original object, whereas altering the object's value - the pointer to an object - leads to pointing at something different. Consequently, any other references to the initial object persist, such as one used for passing the object to the dialog, rendering the original object immutable. This is where the utility of Object.assign() comes in (a function you're likely already using to craft temporary data objects). Therefore, it's imperative to revise your method of 'saving' from:

this.room = this.tempRoom;

to

Object.assign(this.room, this.tempRoom);

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

Leveraging i18next to substitute a variable with a ReactNode component

My translation json file contains the following translation: "pageNotFound": { "description": "The page could not be found. Click {{link}} to return to the home page" }, I am looking to replace the link variable with a ReactRouter <Link> Within ...

The p-calendar feature is experiencing compatibility issues with Internet Explorer, Edge, and Firefox

While I've had success using primeng p-calendar on Google Chrome, I've encountered an issue where the date-picker does not open upon clicking the text box on other browsers. Below is the snippet of HTML code I utilized: <p-calendar [(ngModel ...

Checking for Object Equality in TypeScript

I'm working on a TypeScript vector library and encountered my first failed test. The issue revolves around object equality in TypeScript/JavaScript, and despite searching through TypeScript's official documentation (http://www.typescriptlang.org ...

tips for obtaining the highest value among multiple keys within an array

How can I find the maximum value among multiple keys in an array? I previously attempted to find the maximum values for just three keys. getMaxValuefromkeys(values: any[], key1: string, key2: string, key3: string) { var val1 = Math.max.apply(Math, v ...

When using the `Document.write()` method, an error is returned stating, "Uncaught TypeError: Cannot read property 'document' of null"

I am currently integrating Angular2 into a website as the front-end framework, and it will be displayed on another website using an iframe. When working with the HTTP post method, I am able to receive a JSON response. Here is the API Post method that retu ...

After the initialization of the app, make sure to provide an InjectionToken that includes the resolved configuration

During the initialization of the application, I am looking to retrieve the configuration using a factory that will be resolved through the APP_INITIALIZER provider. export function loadConfig(): () => Promise<Config> { // return promised confi ...

Guide on implementing Regular Expressions in Directives for validation in Angular 8

Managing 8 different angular applications poses its unique challenges. In one of the applications, there is a directive specifically designed for validating YouTube and Vimeo URLs using regular expressions. Unfortunately, once the RegExp is declared, ther ...

The JSX component is unable to utilize the object

When working with Typescript in a react-three-fiber scene, I encountered an error that GroundLoadTextures cannot be used as a JSX component. My aim is to create a texture loader component that loads textures for use in other components. The issue arises f ...

The Angular frontend is making me wait for the transfer of 20mb during the initial load

My Full Stack Website is built using the MEAN stack. The front end was developed in Angular5 and deployed on the server. However, I am encountering an issue where it takes a significant amount of time to load for the first time as it needs to download appr ...

Unexpected token in catch clause in React Native TypeScript

Despite having a fully configured React Native Typescript project that is functioning as expected, I have encountered a peculiar issue: Within all of my catch blocks, due to the strict mode being enabled, typescript errors are appearing like this one: htt ...

When attempting to set a variable type using ":URL", an error is generated

When I created a file named "test.ts" in VSCode, I included the following code: var data = "https://a.b.c/d/e/f"; var url = new URL(data); console.log(url.protocol); After pressing F5, the output was "https:". However, when I added a type declaration like ...

Playwright failing to execute GraphQL tests due to TypeScript configuration problems

I'm facing an issue with my repo where I am running tests using Playwright against a graphQL URL. Despite configuring the tests, there is an error indicating that the environment variable defining the environment cannot be found. The repository in qu ...

Sharing information between sibling modules

Currently, I am faced with the challenge of transmitting data between two sibling components within the following component structure. The goal is to pass data without changing the relationships between these components. I prefer not to alter the componen ...

Is it possible to save an externally retrieved image locally using Angular?

I'm brand new to Angular and trying to work with a QR code image generated from the angularx-qrcode library. Here is the code snippet: <qrcode [qrdata]="'Your QR code data string'" [size]="256" [level]="'M'"></qrcode> ...

JavaScript alert box

I'm fairly new to the world of web development, with knowledge in CSS & HTML and currently learning TypeScript. I'm attempting to create a message icon that opens and closes a notifications bar. Here's where I'm at so far: document.getE ...

Utilizing shared state in React components through props

Currently, I am utilizing a shared global state in the following manner: interface DashboardProps extends React.Props<Dashboard> { globalState? : GlobalState } export class Dashboard extends React.Component<DashboardProps, any>{ } Withi ...

Rearranging items within an array in a React component

Currently, I am facing a situation where I have created a list that dynamically adds a React Node upon clicking a button. The final layout of the model looks like this: https://i.sstatic.net/fG37r.png Here is the code snippet for your reference: import ...

Expanding the visual in a spacious display with the help of ng-carousel from the Bootstrap framework

I have created a slider with multiple images on a website using Angular 4. The slider is displayed in a small area of the webpage and I would like to add a feature where the user can click on an image to view it in a larger screen or window. This could i ...

The handler for the ActionSheet is unable to retrieve the class variable

Exploring the capabilities of the Ionic Framework, I delved into using ActionSheet and ActionSheetController for a Proof of Concept. Everything was functioning smoothly until I came across an unexpected error. When assigning a function as a handler that I ...

There seems to be an issue with the Angular9 window.open() function as it is

I've encountered a strange issue where the code runs successfully on my local environment, but in production, I keep receiving a bad request 400 error. Any insights on what might be causing this? Here is the URL that triggers the bad request error: h ...