CodexBloom - Programming Q&A Platform

Form data not persisting after navigating between tabs in Angular using Reactive Forms

πŸ‘€ Views: 132 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-08
angular reactive-forms tabs typescript

This might be a silly question, but Quick question that's been bugging me - I'm working on an Angular application where I'm using Reactive Forms to manage user input across multiple tabs. I noticed that when I switch between tabs, the form data is lost, and I get the following behavior in the console: `want to read property 'getRawValue' of undefined`. I've set up my form in the main component, and I'm trying to continue the data as the user navigates through different tabs. I thought that using a service to hold the form state between component instances would solve the scenario, but it seems the form controls are getting reinitialized every time I switch tabs. Here’s a simplified version of my code: In `app.component.ts`: ```typescript import { Component } from '@angular/core'; import { FormBuilder, FormGroup } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', }) export class AppComponent { myForm: FormGroup; constructor(private fb: FormBuilder) { this.myForm = this.fb.group({ name: [''], email: [''], }); } saveData() { // Attempt to save form data to service } } ``` In `app.component.html`: ```html <form [formGroup]='myForm'> <input formControlName='name'/> <input formControlName='email'/> </form> <app-tab [form]='myForm'></app-tab> ``` In `tab.component.ts`: ```typescript import { Component, Input } from '@angular/core'; import { FormGroup } from '@angular/forms'; @Component({ selector: 'app-tab', template: `<div>Tab Content</div>` }) export class TabComponent { @Input() form: FormGroup; } ``` I’ve already tried using a shared service to store the form data, but it seems like the input bindings aren't updating properly. I'm also not sure if I should be using `ngOnChanges` to listen for changes in the form object. Can anyone suggest a strategy to ensure the form data continues while navigating between tabs, or provide insight into how to avoid this behavior? Any help would be greatly appreciated! I'm working on a web app that needs to handle this. Has anyone else encountered this? How would you solve this?