【问题标题】:how to access element inside angular component $postLink如何访问角度组件 $postLink 中的元素
【发布时间】:2017-09-22 16:50:21
【问题描述】:

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

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

我是不是写错了?还是我必须使用对于单向绑定而言不是最佳的指令?

关于.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;

关于.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;

关于.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;

关于.html

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-14
      • 1970-01-01
      • 2016-09-05
      • 1970-01-01
      • 1970-01-01
      • 2019-04-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多