Siebren K.
Siebren K.

Reputation: 41

Polymer 2 define global variables

I recently started working with Polymer 2.0, and so far i am in love with it. I am used to Angular in combination with typescript, and i loved how easy it was to define global variables.

Wanted outcome: Let's say i have a variable named: "Username" in the login page. The var Username is currently "Guest", so in my welcome-page i have the message "Hello Guest!". The username in the login page changes from guest => not-a-guest The welcome-page now says: Hello not-a-guest!".

Is there a way to do this without passing the variable like ? Because everytime I want to use the username property, i now have to pass the username like above. (so if i need the username in a child of a child of a child component, I now have to pass the username to all parents aswell). Now ofcourse this is about a user so in this case, localstorage/sessionstorage would be alright, but this is just an example. I'd like to use the global defining for something else, and saving that in localstorage would not be ideal.

I found a lot of Polymer 1 solutions, but i'd love to have my application in full Polymer 2.0.

Thanks a ton!

Upvotes: 1

Views: 1946

Answers (3)

Caribouflex
Caribouflex

Reputation: 781

There is the iron-meta element that can be used to do exactly what you created.

Upvotes: 0

Siebren K.
Siebren K.

Reputation: 41

I figured and make a webcomponent myself. usage:

// Login component
// Define global variable
<brum-global-var key="username" value="{{username}}"></global-variable>

// welcome-page 
// Use global variable
<brum-global-var key="username" value="{{username}}" readonly></global-variable>

Upvotes: 2

Arnau
Arnau

Reputation: 455

One option would be to use a mixin class and extend it in whatever component you need it. Read more here.

Upvotes: 1

Related Questions