Search code examples
javascriptangularjsangularjs-directiveangularjs-components

How to select element inside Angular 1.5 component?


For component, I can no longer refer to Elem or Attr like I used to in its father -- directive, by taking them as arguments inside link or post.

What is the best way to select element like I used to in directive? Did it change the way how it should be done?

Why is it not documented in the component document for the Angular 1.5x?


Solution

  • You could do the same thing inside component controller by injecting $element dependency. But on controller load $element is not compiled DOM.

    For such case you could use Angular 1.5 component life cycle, like there we have $postLink() which will work as same as like postLink/link function of Angular 1 directive.

    For accessing attribute you inject $attrs service inside controller.

    Component

    myMod.component('myComponent', {
      template: '<h1>Home</h1>',
      controller: function($element) {
        this.test = 'hello world';
        this.$postLink = function(){
          //here you have compiled DOM
          //you can play with element here.
          console.log("Post LInk DOM", $element);
        }
        console.log("Initial DOM", $element);
      }
    });