Home > Software design >  How to avoid component's variable reset after hiding the component?
How to avoid component's variable reset after hiding the component?

Time:08-02

In my angular project, there are 2 components, upload and search component. I use the *ngIf statement to hide and display component as below.

In app.component.html

<!--used @output emiter -->
<app-search-bar (searchAllEvent)="searchAllEventReceiver()" (upload)="uploadReceiver()">

<app-search-all *ngIf="..." ></app-search-all>

<app-upload *ngIf="..."></app-upload> 

In app.component.ts

uploadReceiver(){...}
        
searchAllEventReceiver(){...}

In upload-component.html there are a form and I use typescript to submit form value like below:

uploadName : string = "";
constructor(...) { this.uploadForm ...}
onSubmit (data : any){this.uploadName = data.name ; ...}

Problem is, after entering value or submited the value in upload component's form and opening the search component with the event emitter. The upload component's value is wiped. How can I prevent the erase of the form value?

I heard that observable, subscription and all that might be the solution. But is there any other ways to work around?

CodePudding user response:

In this case, you can replace *ngIf with hidden.
Because hidden attribute hides the element without removing it from the DOM (as ngIf does) and does not restart the lifecycle

  • Related