-1

I'm having difficulty in recognizing when should I

  • create attribute directive,
  • realize that I need to create attribute directive,
  • use input and output properties

What is the need of attribute directive?

I tend to include all logic into one component, I know its definition but practically, I can't find examples.

What are the best practices?

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
john doe
  • 39
  • 8
  • Possible duplicate of http://stackoverflow.com/questions/34613065/what-is-the-difference-between-component-and-directive – Avnesh Shakya Jan 01 '17 at 11:13
  • Avoid putting the tags in the title unless it's a necessary part of the question. Best practices requests are off-topic on stack overflow. – Emile Bergeron Jan 03 '17 at 02:43

1 Answers1

0

Directives can be used to manipulate DOM element. It's so useful when you wanna make a custom (third party) directive that can be used by other programmers in your team or world.

Basically there are three types of directives.

1) Structural Directive
2) Attribute directives
3) Component Directive(with template)


1) Structural Directives usually manipulates structure of view/template. Eg. *ngFor will generate element according to your list count. *ngIf will display/hide view according to passed value.


2) Attribute directive allows you to add an attribute on DOM element and then you can do many things with that DOM element.

eg.

<p myColor >Color me!</p>    //<<< this helps you to grab DOM element using ElementRef and then I'll color it as shown below.

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

here myColor is just an attribute directive as it is added to the DOM element as an attribute but this attribute doesn't accept any value yet.

Now let's add a value to myColor attribute,

<p [myColor]="color">Highlight me!</p>   


@Input : Here we are passing color variable(Angular2 bindings) so in directive we must have a mechanism to receive it. So we should use @Input API as we are going to get value from parent component(you can consider directive as a child of parent)
@Output : If you want directive to emit some value that should be received by parent component then you should use @Output API
micronyks
  • 54,797
  • 15
  • 112
  • 146