1
votes

I could use some help.

Lets say i have a directive:

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

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

And i have a component

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();
  }

}

Component template:

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

app.component.html

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

All good. I get hey hey on console. But i want to attach directive to component selector like so:

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

And be able to call directive methods inside component class. How? Tnx for your time

1

1 Answers

0
votes

Try accessing it like you would a Provider (in the constructor).

In your example...

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();
  }

}

I've added the @Optional in case the directive is optional on your component, which may occur in some cases.

Oh, and this also works on Directive to Directive..

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

This was tested on my project and works. The property was even ready in the constructor. Just keep an eye on any cyclical references (e.g. component calls the directive, the directive calls the component, etc..)

Happy Coding.