Search code examples
javascriptangularecmascript-6angular-directiveangular-components

how to access element inside angular component $postLink


using this repo for angular boilerplate https://github.com/AngularClass/NG6-starter

But I found hard to access the dom inside angular component's $postLink phase.

Am I coding it wrong? Or do I have to use directive which is not optimal for one way binding?

about.component.js

import template from './about.html';
import controller from './about.controller';
import './about.scss';

let aboutComponent = {
  restrict: 'E',
  bindings: {},
  template,
  controller,
};

export default aboutComponent;

about.controller.js

class AboutController {
  constructor() {
    this.name = 'about';
    this.$postLink = ($element) => {
      console.log($element); // here is when I want to utilize the element!
    }
  }
}

export default AboutController;

about.js

import angular from 'angular';
import uiRouter from 'angular-ui-router';
import aboutComponent from './about.component';

let aboutModule = angular.module('about', [
  uiRouter
])

.config(($stateProvider) => {
  "ngInject";
  $stateProvider
    .state('about', {
      url: '/about',
      component: 'about'
    });
})

.component('about', aboutComponent)
.name;

export default aboutModule;

about.html

<section>
  <navbar></navbar>
  <h1>{{ $ctrl.name }}</h1>
  <section>
    About us.
  </section>
</section>

Solution

  • You can't get $element(directive element) from $postLink lifecycle hook. You have to inject $element inside controller constructor to get directive element inside directive.

    class AboutController {
      static $inject = ["$element"]
    
      constructor($element) {
        this.name = 'about';
        this.$element = $element;
      }
      // better move out $postLink outside controller.
      $postLink = () => {
         console.log($element); 
      }
    }
    

    export default AboutController;