使用这个仓库来做角度样板
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>

最佳答案

您无法从$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);
  }
}


导出默认的AboutController;

07-24 09:43
查看更多