如何访问角度组件$ postLink中的元素

时间:2017-04-25 15:13:32

标签: javascript angular ecmascript-6 angular-directive angular-components

将此回购用于角度样板 https://github.com/AngularClass/NG6-starter

但我发现很难在component $postLink阶段内访问dom。

我编码错了吗?或者我是否必须使用对于单向绑定不是最佳的指令?

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>

1 个答案:

答案 0 :(得分:4)

您无法从$element生命周期钩子获取$postLink(指令元素)。您必须在控制器$element中注入constructor以在指令中获取指令element

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;