Is it possible to maintain component data in Angular while also incorporating dynamic components?

All the code you need can be found here:

https://stackblitz.com/edit/angular-keep-alive-component?file=src/app/app.component.ts

Is it possible to maintain the state of entered values when switching components? I am currently utilizing dynamic component rendering with Component Factory Resolver, but I want to retain entered values when changing components... Is this achievable in Angular 9?

In Vue.js, there is a keep-alive directive for this purpose. Can something similar be achieved in Angular 9 as well?

Here is an example of what I am looking for:

1. Render first component ->

2. Enter some test data in the input field ->

3. Change to the second component ->

4. Return to the first component and see the previously entered 'TEST DATA'

  public createComponent(component: number): void {
    const currentComponent = this.components[component];
    let componentFactory = this.componentFactoryResolver.resolveComponentFactory(
      currentComponent as any
    );
    let viewContainerRef = this.adHost.viewContainerRef;
    viewContainerRef.clear();
    let componentRef: any = viewContainerRef.createComponent(componentFactory);
    componentRef.instance.outputEventData.subscribe((val: Object | any) => {
      if (val) {
        this.sendFilter.emit(val);
      }
    });
    setTimeout(() => {
      componentRef.instance.destroyComponent.subscribe((val: any) => {
        if (val) {
          viewContainerRef.clear();
        }
      });
    }, 0);
  }
}

Answer №1

To establish a data service, start by setting up an rxjs Subject within the service. Next, inject this data service into both of your components. In the first component, subscribe to the Subject. Then, in the second component, whenever you enter input, trigger subject.next(typeInput). This action will automatically update the data in the subscription of your first component.

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

Determining if an item is empty, undefined, or null in Angular: a guide

I received a .json file structured as data [0 ... n]. Each position in the data array contains an object with various attributes, such as: {photo1, photo2, photo3 ... photoN} For a visual representation of how the json file is formatted, you can check ...

I am attempting to retrieve a value from a dropdown menu but I am encountering difficulties

Within the structure of a Vue component's template, I have the following code: <td> <select id="papel" @change="intervChange(row)"> <option value="Apreciador">Apreciar</option> <option value="Assessor">Assessor ...

Exploring locations using the Google Geolocation API

I have a website and am trying to determine the location of my visitors. I came across this code on Google Code: <script type="text/javascript" src="gears_init.js"></script> <script type="text/javascript"> var geo = google.gears.factory ...

jQuery does not have the capability to automatically calculate Value Added Tax on form submissions

I have included this section in my form to calculate the value added tax (VAT): <div class="col-md-4"> <div class="form-check"> <input type="radio" id="vat_on" name="vat" value=&q ...

Repositioning a variable number of divs as the cursor hovers over the target area

Can anyone show me how to generate div elements in a loop using jQuery and change their position with the "mouseover" function? I've tried some code, but the positioning isn't changing correctly. Any suggestions on what needs fixing? var r, g, ...

Angular's recurring problem with reusable components

Exploring Angular's reusable components is new to me, and I am uncertain about how to effectively reuse the component once it has been created. In my project, I have three main components: parent, container, and reusable components. In 'parent.c ...

What steps should I take to troubleshoot an error with accessing 'request.body' within an async function that is returning a 'ReadableStream' object instead of the data I was expecting?

While developing my CRUD functionality in Next.js with TypeScript and Prisma, I encountered an issue with the PUT method. The GET method handler works fine, but for some reason, the PUT method is causing errors that I'm struggling to resolve. When in ...

encountering an issue with server-side rendering of React causing an error

Node.js has been a bit of a challenge for me, especially when it comes to working with react and express. I have been struggling to find comprehensive tutorials and troubleshooting resources, leading me to ask minimal questions in the correct manner. While ...

Keep the Bootstrap modal open while the JavaScript validation is running, and redirect the form action if the validation is successful

When trying to execute the submit event from a form, my code is supposed to keep the modal open if validation fails. However, for some reason, this functionality is not working as expected. var myForm = document.updteform; var condition = true; if ...

Manipulating the "placeholder" attribute with Knockout.js and JSON data

Is it possible to use the placeholder attribute with data-bind? I am encountering an error message ([object object]). Can someone help me figure out how to properly utilize it? html: input id="comments" class="form-control" data-bind="attr: { placeholde ...

Utilizing ngFor to iterate over items within an Observable array serving as unique identifiers

Just starting out with Angular and I'm really impressed with its power so far. I'm using the angularfire2 library to fetch two separate lists from firebase (*.ts): this.list1= this.db.list("list1").valueChanges(); this.list2= this.db.list("list2 ...

Efficient method invocation for objects within an array using functional programming techniques

Is there a way to execute a method that doesn't require arguments and doesn't return anything on each object within an array of objects that are all the same type? I've been trying to find a solution without resorting to using a traditional ...

How can I show the number of items in my filtered data using AngularJS?

My data array holds objects in JSON format. var users = { 'New':{ {Name:'One'}, {Name:'Two'} }, 'Old':{ {Name:'Three'}, {Name:'Four'} } This piece of code is used to disp ...

Take away the CSS class from an element after reCAPTCHA verification is complete in Next.js

I'm struggling with removing the CSS class btn-disabled from the input button element upon successful verification of a form entry. I have implemented a function called enableForm to remove the btn-disabled CSS class when reCAPTCHA is verified. Howe ...

Retrieve JSON data from a RESTful API by utilizing pure javascript

I'm eager to try out the Wikipedia search API in JavaScript, even though it might be simpler with jQuery. I want to make sure I understand the basics first before turning to frameworks. Below is the code I've come up with, but for some reason, I ...

Display a pop-up alert message when the session expires without the need to manually refresh the page

I have a query regarding the automatic display of an alert message. Even though I have set the time limit to 10 seconds, I still need to manually refresh the page for the alert message to appear. The alert message should notify the user that the session ...

The attribute 'limitTags' is not present in the type 'IntrinsicAttributes & AutocompleteProps'

The Versions of Material UI and Lab I am Utilizing "@material-ui/core": "^4.8.3", "@material-ui/lab": "^4.0.0-alpha.44", Visit the component here Snippet of My Code <Autocomplete multiple limitTags={2} id="multiple-limit-tags" ...

Modifying ID styling using JavaScript on Internet Explorer

I need to change the CSS display property from none to block using JavaScript, but only for Internet Explorer. My current code is not working for the ID #backfill-image. <script> function checkForIE() { var userAgent = navigator.userAgent; ...

Troubleshooting the issue with utilizing the ng-repeat directive to loop through images in Angular JS

Embarking on my initial website development journey with Java and Spring Boot, I've hit a stumbling block in the front-end realm. Being a newbie, I'm struggling to identify and resolve the issue at hand. Problem title: How do I ...

Utilizing MSAL's loginRedirect within an Ngrx Effect: A step-by-step guide

Is there a way to utilize Msal angular's loginRedirect(): void function instead of loginPopup(): Promise in an Ngrx Effect? I've been able to successfully implement the loginPopup() method, but since loginRedirect() has a void return type, it di ...