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

how to access element inside angular component $postLink

将此 repo 用于 angular 样板文件 https://github.com/AngularClass/NG6-starter

但我发现很难访问 angular 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>

您无法从 $postLink 生命周期挂钩中获取 $element(指令元素)。您必须在控制器 constructor 中注入 $element 才能在指令中获取指令 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;