1

How to define global variables in angular7 and how it helps in maintaining the form data

  • 1
    in a component class if you have declare `abc: any` it's global variable for the particular component or if you think to for project then declare `abc: any` in service. – Abhishek Jan 29 '19 at 06:57
  • will u please give me an example – Sai chaitanya Jan 29 '19 at 07:02
  • try it your self and share your code here then i can help you – Abhishek Jan 29 '19 at 07:07
  • As Abhishek said, you can use single service which declared and provided by the root module (app.module.ts) and being imported into each component. But here is a simple way like this --> window["your-variable-name"] = value – Coco Jan 29 '19 at 09:10
  • @陈杨华 just a quick note, using `window` (or `document`, `location`, etc...) is not always a good practise in my opinion, since if some day you'll need to implement Angular Universal or in general some server side rendering stuff, function like `document`, `window` and even `location` would not work properly and give errors when compiling and executing. But of course, if you are sure you won't use server side rendering this is not a problem. (also sessionStorage and localStorage have the same limitation, but luckily [there are some abstractions](https://stackoverflow.com/a/39098748/9653205)) – Deadpool Jan 29 '19 at 09:44
  • hahaha, thx for your tip. but it seems like asker is a beginner of angular. – Coco Jan 29 '19 at 10:00

1 Answers1

0

1) KEEPING DATA IN MEMORY

First of all, you will need to save your form data into a local object in your component.
So, starting with your component, I would expect something like:

foo.component.html

<!-- ... more stuff here ... -->

<!-- IMPORTANT: [(ngModel)]  -->
<input type="text" id="name" class="fooclass" required [(ngModel)]="formvalues.name" placeholder="Name goes Here" name="name" />

<!-- ... more stuff here ... -->

foo.component.ts

//more stuff here
formvalues: MyForm;

constructor ( /* ... */ ) {
   this.formvalues = new MyForm();
}

Then, MyForm is a class, and classes can be imported and used inside multiple components without any problem. You will declare this class in another file, like:

myform.class.ts

export class MyForm {
  name: string = '';
  surname: string = '';
}

Now, go back inside foo.component.ts. We will add a couple of functions to save and restore state.
We will save in sessionStorage, but you can use localStorage if you wish.
Basically, sessionStorage lives in the browser tab and is not visible in other tabs, if you close the one you are, its content is lost. localStorage lives forever and you have to manually clean it.
You can read more about sessionstorage and localstorage here.

saveState() {
  if(this.formvalues && this.formvalues!=null){
    var tosave: string = JSON.stringify(this.formvalues);
    sessionStorage.setItem('myappFormData',tosave);
  }
}

resumeState() {
  var restorestring = sessionStorage.getItem('myappFormData');
  if(restorestring && restorestring!='' && restorestring!=null && restorestring!='null'){
    var restore: MyForm = restorestring as MyForm;
    this.formvalues = restore;
  }
  else {
    this.formvalues = new MyForm();
  }
}

Now, you can call this.resumeState(); inside NgOnInit() of your component and this.saveState(); when...well, I don't know, when the user saves the form via button click I think. It depends from what the user should do.

If you use Angular Universal and/or Server-Side rendering, sessionSotrage and localStorage will not work. Luckily, Angular provides some abstractions for this.

2) COMMUNICATING BETWEEN COMPONENTS

If you want real time communication between components, I suggest you to use a service as middleware, like:

foobar.service.ts

@Injectable()
export class FooBarService {

  private value = new BehaviorSubject<MyForm>(null);
  value$ = this.value.asObservable();

  //more stuff here...

  updateValue(newVal:MyForm) {
     this.value.next(newVal);
  }
}

Now components can subscribe like:

myservice.value$.subscribe(res => this.formvalues=res);

And push values like

myservice.updateValue(formValues);

Notice that:

  • I've used a BehaviorSubject, if you don't want a default value, you can use a Subject

And

  • Values inside services lives as the application lives. So if an user quits, the values are lost. If you save them inside localStorage they can persist

Let me know in the comment if you have any doubts!

Deadpool
  • 1,031
  • 3
  • 19
  • 35