Is there a way to maintain formdata between components in Angular?

With only the tools of @Input, @Output, routing, and activatedRoute at my disposal, I set out to create a dynamic application.

In this project, there are two crucial components: addbook and showbook.

The addbook component features a form with a submit button designed to store all the entered data upon submission.

Meanwhile, the showbook component is responsible for displaying the saved form data.

Both components are neatly integrated within a navigation bar consisting of anchor tags. One leads to the addbook component where users can input their data which should be saved upon submission. The other directs users to the showbook component where they can view the stored form data.

To achieve this functionality, I have implemented a template-driven form that triggers a function on submission:

this.route.navigate(['showbook', bookID])

Furthermore, I configured the route path as 'showbook/:id' and associated it with the showbook component using RouterModule.forRoot([routes]). Within the showbook component, activatedRoute was utilized to extract and display the form data by retrieving the parameters.

RouterModule.forRoot([{path:'showbook/:id',component:showBookComponent}]) // in app module ts
this.activatedRoute.params.subscribe(params=>{
this.bookId = params['id']
})

Despite successfully displaying the form data upon submission, my current solution fails to save the data persistently. The requirement stipulates that the data must be saved until accessed via the showbook component without relying on local storage implementation.

Answer №1

If you want to store and retrieve data, you can utilize the service.

  1. Once the form in addbook is completed and saved, save the data in the service.
  2. When you visit showbook, fetch the data from the service.

For instance:

data.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  formData: Object;

  constructor() { }

  // Set the value
  setFormData(data){
    this.formData = data;
  }

  // Get the value
  getFormData(){
    return this.formData ;
  }
}

In addbook.component.ts

Start by importing the service.

import { DataService } from '../../data.service';

Inject the service in your constructor

constructor(private dataService: DataService){}

In your save button function

this.dataService.setFormData(data);

In showbook.component.ts

Begin with importing the service.

import { DataService } from '../../data.service';

Inject the service in your constructor

constructor(private dataService: DataService){}
 

Show the form data in the init function

 ngOnInit(): void {
    this.formData = this.dataService.getFormData();
  }

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

Eliminate server-side functionality from the React project's boilerplate template

After cloning and installing the project from https://github.com/react-boilerplate/react-boilerplate, I realized that I only need the client-side portion as I intend to use a pre-existing server (express) for my application setup. Below is an excerpt f ...

Unusual behavior observed during npm update operation

Just starting out with Angular and NPM, I have encountered a puzzling situation. I have two Angular-CLI projects. When I run npm update --save in one project, the dependencies (including @angular dependencies) are updated from version ^5.2.0 to ^5.2.3 in ...

The Photoswipe default user interface cannot be located

While attempting to incorporate PhotoSwipe into my website, I encountered an uncaught reference error related to The PhotoswipeUI_Default is not defined at the openPhotoSwipe function Below is the code snippet that I have been working on: <!doctyp ...

Retrieve the array from the response instead of the object

I need to retrieve specific items from my database and then display them in a table. Below is the SQL query I am using: public async getAliasesListByDomain(req: Request, res: Response): Promise<void> { const { domain } = req.params; const a ...

Tips for extracting header ID from the HTML/DOM using react and typescript

I developed a unique app that utilizes marked.js to convert markdown files into HTML and then showcases the converted content on a webpage. In the following code snippet, I go through text nodes to extract all raw text values that are displayed and store t ...

How can I ensure a successful redirect to react-router root path after saving to MongoDB in Express?

As a newcomer to React and react-router, I may be making some rookie mistakes in my project. Currently, I am constructing a web application with React and react-router as the frontend server, paired with Express and MongoDB for the backend. To communicate ...

Utilizing withRouter outside a component to navigate through historical data

I'm still getting the hang of react router and encountering some challenges. I can easily use history within a component without any issues. However, when trying to access history from a function outside the component, I run into problems. Despite my ...

Filtering text for highlighting in Vue.js is a breeze

Struggling to create a text highlight filter using vuejs. The task involves iterating through an array of words, highlighting any matches with a span and class. However, I'm facing difficulty in getting the data to return with proper HTML formatting i ...

What is the reason behind the default disabling of bootstrap multiselect options?

Just diving into the world of bootstrap and I'm puzzled as to why my simple multiselect options aren't responding when clicked. UPDATE The first multiselect option on the test-site linked below is the one giving me trouble. I've tried it o ...

Load all components in advance when implementing lazy loading for individual components in routing

Utilizing standalone components in angular 17 allows for direct lazyLoading of components without the need for modules. However, a question arises on how to preload in this scenario. Previously, when lazy loading modules, the strategy used was withPreloadi ...

Analyzing elements within an array of objects

Here is an array of objects I have: const cart = [ { group: "group 1", qtd: 12, value: 65, term: 20 }, //index 0 { group: "group 1", qtd: 10, value: 100, term: 20 }, //index 1 { group: "group 1", qtd: 18, value: 40, term ...

Starting an AngularJS module without an HTML page may seem like a daunting task,

I am currently developing a browser extension project using AngularJS. Within the background.js file (which contains the code that runs in the background), I have created a module with a run block. var myExtensionModule = angular.module('myExtension ...

Tips for streamlining the filter function using replace and split:

Currently, I am utilizing a filter function alongside replace() and split(). Here is the code snippet: jQuery('table .abc').filter((i, el) => jQuery(el).text(jQuery(el).text().replace('a', 'b').split(' ')[0] + &ap ...

Hide form data upon submission

I have a form and I'm looking to send hidden input using JavaScript. How can this be achieved? Example: <input id="total" type="hidden" value="" name="total" /> When the submit button is clicked, I would like to set its value. ...

Switching a Rails/Ajax form from create to update mode upon submission

While experimenting with a star ratings page, I encountered an issue where the form element remained in "Create" mode instead of updating to an "Update" method after submission. The rating form is ajaxified, but it lacks the functionality to dynamically sw ...

Summing Values with Linq.js Filter

Can you apply a filter in Linq.JS using SUM? This is my attempt: var query = Enumerable .From(self.data()) .Where("$$.Sum($.percent) > 100") .ToArray(); Issue encountered: linq.js: Uncaught TypeError: $$.Sum is ...

Having trouble with a Reactjs Facebook login library - update the componentClicked function to be async

Currently, I am working on incorporating Facebook login into my React application using Redux. Within my loginUser.js file, the "FacebookLogIn" component appears as follows: <FacebookLogin appId="375026166397978" autoLoad={true} fields="name, ...

Enhancing jQuery UI elements (Customizing jQuery Datepicker to prevent incorrect entries)

My goal is to enhance the functionality of the jQuery UI Datepicker by adding validations. I have spent considerable time searching the internet for help without success. Although I came across a similar question on Stack Overflow jquery-datepicker-functi ...

deployJava.js injects a new <embed> element into the header section of the webpage

I've ran into an issue with the Java applets on my website. I included the deployJava.js load tag in the head section of the page, but when I look at the resulting HTML in Chrome debugger, this script seems to be breaking my head content and starting ...

Toggle the visibility of table rows using checkboxes

I'm working with checkboxes to toggle the visibility of specific rows in a table based on their content matching the selected checkbox values. Checkboxes: <input type='checkbox' name='foo1' value='foo1' v-model="sele ...