Angular: ensure the form reverts to its initial value when the modal is closed and reopened

I am facing an issue with my items section. When I click on an item, a modal window opens allowing me to edit the text inside a textarea. However, if I make changes to the text and then cancel or close the modal, upon reopening it, the previously modified text remains. My objective is to reset the text to its original state before any modifications were made when closing the modal.

Could you provide some guidance or suggest a solution for this problem?

<form [formGroup]="editForm" (ngSubmit)="editItem()">
  <textarea rows="3" formControlName="text"></textarea>
  <button type="submit">Save</button>
  <button type="button" (click)="closeModal()">Close</button>
</form>
export class EditItemComponent implements OnInit, OnChanges {
  @Input() item: Item;
  editForm: FormGroup;

  ngOnInit(): void {
    this.editForm = new FormGroup({
      text: new FormControl('', [Validators.required, Validators.minLength(3)]),
    });
  }

  ngOnChanges(): void {
    this.editForm.controls.text.setValue(this.item.text);
  }

  editItem():void {
  //logic for editing item
  }

  closeModal(): void {
    //logic for closing modal
    //I am aware that I can simply revert the editForm text back 
    //to its original state, but I am seeking a more generic solution 
    //that can handle various scenarios such as clicking away from the modal 
    //or pressing the escape key to close it.
  }
}

Answer №1

The problem at hand seems to be related to editing the form while the modal is active, which results in changes to the value in the text field of the form. Consequently, if the modal is closed and reopened, the same value remains in the text field within the modal.

One solution could involve either enclosing the entire form within the modal itself to ensure a clean state each time it is opened, or incorporating a feature similar to what can be found in Angular Material's MatDialog.

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

List with pulldown options

I am trying to implement a drop-down list with bullets using Angular 2, JavaScript, and CSS. Although I have managed to create the drop-down list, I am facing difficulty in adding bullets to the list items. Unfortunately, I have found that jQuery and Boot ...

"In the realm of RxJS, there are two potent events that hold the power to

In my current situation, I encountered the following scenario: I have a service that makes Http calls to an API and requires access to user data to set the authentication header. Below is the function that returns the observable used in the template: get ...

Angular 6 - The requested resource does not have the necessary 'Access-Control-Allow-Origin' header

I am currently working on an Angular 6 project that includes a service pointing to server.js. Angular is running on port: 4200 and Server.js is running on port: 3000. However, when I try to access the service at http://localhost:3000/api/posts (the locat ...

Updating the legend boxes of a chart in Chart Js to match the style of the graph lines

I need assistance updating the legend boxes of my graphs with graph line style. https://i.sstatic.net/zhi4L.pngActual Consumption https://i.sstatic.net/dAjlp.png Average Use https://i.sstatic.net/YMC7I.png Here is the code snippet I am currently using, ...

Struggling to accurately capture the values from checkboxes and dropdown selections to ensure the correct data is displayed. Assistance is needed in this

I am facing challenges in retrieving the accurate data for display from Mat-Select and Mat-Checkbox components. My goal is to capture the selected values from users and perform if-else statements to validate conditions, displaying the correct data view if ...

When trying to use `slug.current` in the link href(`/product/${slug.current}`), it seems to be undefined. However, when I try to log it to the console, it is displaying correctly

import React from 'react'; import Link from 'next/link'; import { urlFor } from '../lib/clients'; const Product = ({ product: { image, name, slug, price } }) => { return ( <div> <Link href={`/product/ ...

Dynamic class/interface in Typescript (using Angular)

Is there a way to achieve intellisense for an object created with a dynamic class by passing parameters? Here is the code snippet: Main: let ita: any = new DynamicClass('ITA'); let deu: any = new DynamicClass('DEU'); The DynamicClass ...

PHP Email Form Sending Duplicate Emails to Recipients

My PHP mail form is set up to use AJAX & jQuery for validation and submission. Everything appears to be working fine, but the client receiving multiple copies of each email sent by the form. The number of duplicates ranges from 1 to 10 with no clear pa ...

Assistance with Clicking Buttons: Python and Selenium

Recently, I've been attempting to scrape data from an HVAC website. My goal is to input a zipcode, click the submit button, and then extract information on the nearest dealers. If necessary, you can find the website here. The issue arises when I ente ...

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 ...

How can I include components in the precompile array in Angular2 RC4?

After upgrading my Angular2 project to RC4, the router started displaying a warning message in the console when I launch my application: router.umd.js:2466 'FrontpageComponent' not found in precompile array. To ensure all components referred to ...

The constructor for Observable, as well as static methods such as `of` and `from`, are currently

I encountered a challenge in my angular application while trying to create an observable array using rxjs. Here is the code snippet: import { Injectable } from "@angular/core"; import { Observable } from "rxjs/Rx"; import { User } from "../model/user"; ...

Having trouble uploading SharePoint list item with attachment from Angular to ASP.NET Core Web API via NgModel

Recently, I successfully added a SharePoint list item with an attachment from Angular to ASP.NET Core Web API. This was achieved using FormControl in the Angular application. I found guidance on how to upload files from Angular to ASP.NET Core Web API at ...

Can you provide guidance on how to communicate an event between a service and a component in Angular 2?

I'm currently working with angular2-modal to create a modal alert in my application. I am specifically trying to capture the confirm event that occurs when the modal is triggered. Does anyone know how I can achieve this? ...

Can you explain Angular's "rule of unidirectional data flow" to me?

The concept of Angular's "unidirectional data flow rule" is mentioned throughout various sections of the Angular documentation, yet a clear and concise definition of this rule is nowhere to be found. After thorough research, I discovered two somewhat ...

Discover the power of debugging Typescript in Visual Studio Code with Gulp integration

I've been working on setting up an express/typescript/gulp application, and while it's functional, I'm struggling to debug it using source-maps. Here is how I've set it up: Gulp File var gulp = require('gulp'), nodemon ...

Refresh a page automatically upon pressing the back button in Angular

I am currently working on an Angular 8 application with over 100 pages (components) that is specifically designed for the Chrome browser. However, I have encountered an issue where the CSS randomly gets distorted when I click the browser's back button ...

Error occurred in child process while processing the request in TypeScript: Debug Failure encountered

I encountered the following error in TypeScript while running nwb serve-react-demo: Child process failed to handle the request: Error: Debug Failure. Expression is not true. at resolveNamesWithLocalCache (D:\Projects\react-techpulse-components& ...

Surprising Discovery: TypeScript - node_modules Found in Unusual Directory

Is there a way to make TypeScript imports function properly even if the node_modules directory is not directly in the tree? How can I prevent TypeScript from throwing errors when importing something like rxjs from external/node_modules. For Example: Dir ...

Displaying hidden Divs in React Typescript that are currently not visible

I have an array with various titles ranging from Title1 to Title8. When these titles are not empty, I am able to display their corresponding information successfully. Now, my goal is to include a button that will allow me to show all fields. For example, ...