【问题标题】:Accessing angular 2 directive attached to component selector访问附加到组件选择器的 angular 2 指令
【发布时间】:2017-12-14 13:22:33
【问题描述】:

我需要一些帮助。

假设我有一个指令:

import { Directive } from '@angular/core';

@Directive( {
       selector: '[appMyDirective]'
} )
export class MyDirective {
    constructor () {
    }
    seyHey () {
        console.log( 'hey hey!' );
    }
}

我有一个组件

import { Component, OnInit, ViewChild } from '@angular/core';
import { MyDirective } from "../my-directive.directive";

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent implements OnInit {

  @ViewChild(MyDirective) appMyDirective: MyDirective;

  constructor() { }

  ngOnInit() {
    this.appMyDirective.seyHey();
  }

}

组件模板:

<p appMyDirective>
  my-component works!
</p>

app.component.html

<app-my-component></app-my-component>

一切都好。我在控制台上得到嘿嘿。但我想像这样将指令附加到组件选择器:

<app-my-component appMyDirective></app-my-component>

并且能够调用组件类内部的指令方法。如何? Tnx 等待你的时间

【问题讨论】:

    标签: angular2-directives


    【解决方案1】:

    尝试像访问提供者一样访问它(在构造函数中)。

    在你的例子中......

    import { Component, OnInit, Optional } from '@angular/core';
    import { MyDirective } from "../my-directive.directive";
    
    @Component({
      selector: 'app-my-component',
      templateUrl: './my-component.component.html',
      styleUrls: ['./my-component.component.css']
    })
    export class MyComponentComponent implements OnInit {
    
      constructor(@Optional() private appMyDirective: MyDirective) { }
    
      ngOnInit() {
        this.appMyDirective.seyHey();
      }
    
    }
    

    我添加了@Optional,以防该指令在您的组件上是可选的,这在某些情况下可能会发生。

    哦,这也适用于 Directive to Directive..

    @Directive({....})
    export class MyDirective {
      constructor(@Optional() private appMyDirective: MyDirective) { }
    }
    

    这已在我的项目上进行了测试并且有效。该属性甚至在构造函数中已经准备好。只需留意任何循环引用(例如,组件调用指令,指令调用组件等)

    快乐编码。

    【讨论】:

      猜你喜欢
      • 2016-09-08
      • 2018-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-30
      • 2017-01-17
      • 2016-10-03
      相关资源
      最近更新 更多