访问附加到组件选择器的角度2指令

时间:2017-07-10 17:29:55

标签: angular2-directives

我可以使用一些帮助。

假设我有一个指令:

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适合您的时间

1 个答案:

答案 0 :(得分:0)

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

在您的示例中...

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) { }
}

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

快乐编码。

相关问题