Search code examples
angularjsangularjs-components

$postLink vs $OnInit and component life cycle order in angularjs


Hey I have an exprience in building angularjs components and I just wonder why there is a $postlink cycle in every component life cycle. I know that $postLink cycle this hook is called after the controller's element and its children have been linked. When the component elements have been compiled and ready to go, this hook will be fired.

But I have a couple of questions:

1.Does all DOM Manipulations has to be in $postlink cycle or attach event listeners? Why not building a directive for that purpose?

2.What prevent from me doing all DOM Manipluation in $OnInit and what is the difference between $OnInit cycle and $postlink cycle?

Thanks again in advance


Solution

  • 1. Directive or Component postLink?

    You can use both options. On my company we prefer use Directives for DOM manipulation. And keep components simple ;).

    2. onInit() vs postLink()

    The answer is on diference between onInit and postLink.

    onInit() start when your bindings are ready, and component DOM are done. BUT DOM of their childs are not ready.

    postLink() runs when Component DOM and your DOM childs are ready.

    Then, if you only need use component elements use onInit(). But if you need use childrens too, use postLink(). Also, keep on mind my point 1.