简体   繁体   中英

Keep alive component data ? Angular and dynamic component?

All code is here:

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

is it possible to keep the state entered and when the component changes? I am using dynamic component - component factory resolver for rendering component but i want to keep entered values and when change component..... ?

In Vue.js for that exist keep-alive directive but is it possible and using Angular 9?

Example what I need:

Rendering first component ->

type in input whatever example TEST DATA ->

Change component second ->

Return on first component and see previous 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);
  }
}

Create dataService, in data service create rxjs Subject , inject dataService in your two components, in first component subscribe on it, in second component after you type your input call subject.next(typeInput) , data will automatically get updated in your first component inside the subscription

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM