Why are my component bindings undefined in its controller?

前端 未结 9 1780
醉梦人生
醉梦人生 2021-01-31 13:22

I\'m writing a simple angular component. I\'m passing a parameter as a binding and display its value on the screen. All works fine: I can see the parameter being displayed on th

相关标签:
9条回答
  • 2021-01-31 14:06

    I am going to add another answer as a follow up to @jusopi and the accepted answer, just for those who may encounter my issue. In regards to the component, even after the $onInit hook, my data was still null, as the value from the server was still not received. To counteract this (though there may be a better way to handle this situation), I also leveraged the $onChanges hook. $onChanges will return the data that has changed when it is passed it, and you can parse that information, or simply call the binding as this.contactId and it will be updated.

    More details are provided in the documentation: https://docs.angularjs.org/guide/component

    0 讨论(0)
  • 2021-01-31 14:10

    When using angular's components, there is a point where the controller hasn't been wired up via the internal linking. If you're trying to do this in the constructor of your controller, you haven't been linked to the bindings. The Component API exposes a few life-cycle hooks that you can define that will fire at certain times. You're looking for the $onInit hook.

    $onInit() - Called on each controller after all the controllers on an element have been constructed and had their bindings initialized (and before the pre & post linking functions for the directives on this element). This is a good place to put initialization code for your controller.

    per docs - https://docs.angularjs.org/guide/component

    0 讨论(0)
  • 2021-01-31 14:11

    Make sure you use hyphens for bindings in HTML and camelCase for bindings in Javascript.

    app.component("test", {
      bindings: {
        "myContactId": "<"
      }
    }
    
    <test my-contact-id="8"></test>
    

    That's what I always forget to do.

    0 讨论(0)
提交回复
热议问题