Search code examples
javascriptpolymerpolymer-2.x

Polymer - get an element from parent


I have an app that will log in with firebase. I'm using polymerfire for this. Got an main app element: my-app that has these children:

<firebase-app
    auth-domain="my-app-ID.firebaseapp.com"
    database-url="https://my-app-ID.firebaseio.com"
    api-key="my-app-apikey">
</firebase-app>
<firebase-auth
    id="auth"
    user="{{user}}"
    status-known="{{statusKnown}}"
    provider="google"
    on-error="handleError">
</firebase-auth>

<iron-pages selected="{{page}}" attr-for-selected="name">
    <my-loading name="loading"></my-loading>
    <my-home name="home"></my-home>
    <my-dashboard name="dashboard"></my-dashboard>
</iron-pages>

page changes with the statusKnown and user property of the firebase-auth element. While the statusKnown is false the loading page is visible. When the statusKnown is true it selects either home screen, when the user is null or the users dashboard.

  _signInChanged(statusKnown) {
      if(this.statusKnown) {
          if(this.user) {
              this.page = "dashboard"
          } else {
              this.page = "home"
          }
      } else {
          this.page = "loading"
      }
  }

the home screen has an button to signin and then it's clicked it must call the firebase-auth function signInWithPopup(). But the firebase-auth element cannot be accessed from the my-home element. It cannot be found with document.getElementByID or passed as an attribute. Or somehow access if with the parent pointer this.parentElement.$.auth.signInWithPopup()

How can I get the auth element from the child?


Solution

  • You can do it different way. Thanks to events and listeners you will be able to propagate some event to parent and then in parent-element just access firebase-auth using this.$.auth.

    So:

    at my-home element when you are ready to call firebase auth, just call somethind like: this.fire("logIn"); and in parent-elemet inside a ready function write this:

    this.addEventListener("logIn", function() {
      this.$.auth.signInWithPopup();
    }.bind(this));
    

    and that's it.