1
votes

Following is the directive example given on Angular documentation for attribute directive https://angular.io/guide/attribute-directives

import { Directive, ElementRef, Input } from '@angular/core';
@Directive({ selector: '[myHighlight]' })
export class HighlightDirective {
    constructor(el: ElementRef) {
       el.nativeElement.style.backgroundColor = 'yellow';
    }
}

Just below it they explain it with following text

  1. The import statement specifies symbols from the Angular core:
  2. Directive provides the functionality of the @Directive decorator.
  3. ElementRef injects into the directive's constructor so the code can access the DOM element.
  4. Input allows data to flow from the binding expression into the directive.

I am not clear with the fourth point, they say input allows data to flow from binding expression into directive, but in the class no where the Input is used, then how could Angular use it, because previously I read on NgModule documentation, that the import statement on top is not related to Angular

so my understanding is whenever Angular encounters attribute directive, it will create an object using the class HighlightDirective, but since it does not have any reference to Input, how can it get the data flow from binding expression

so in my understanding since we are not accessing data here, we do not need to import Input module at top

2

2 Answers

1
votes

The HighlightDirective directive doesn't have an @Input()

If you look at the source of the *ngIf directive it should become more clear

@Directive({selector: '[ngIf]'})
export class NgIf {
  ...

  constructor(private _viewContainer: ViewContainerRef, templateRef: TemplateRef<NgIfContext>) {
    this._thenTemplateRef = templateRef;
  }

  @Input()
  set ngIf(condition: any) {
    this._context.$implicit = this._context.ngIf = condition;
    this._updateView();
  }

This directive does have an input, and I assume you're familiar with it's use

<div *ngIf="isVisible"

where the value of isVisible is passed to the @Input() ngIf; (in this case a setter but I left it off because in general it's just a field, not a setter)

0
votes

You need not use the Input for this directive because it is placed on a element and we are getting all the properties of the element by placing the directive on top of the element and then directly modifying the element color .

But once you need to pass a value to the directive you will need to use the @Input . like for eg passing the background color dynamically on the go.

See a working example with Input import LINK