1

I'm new to Angular2 and I'm reading the differences between elements, components, directives, etc. and I don't understand why @Directive exist.

I already read the documentation (it's not necessary to link it, thanks, I already checked it) and I've seen that @Component is a particular case of a directive. Also, there are different kinds of directives (Structural, Attributes and the already mentioned Components). However, at the end of the day, I look at some examples of @Directive and I find they can be substituted by an (event) in the corresponding @Component.

Example: the main example of a @Directive in this page @Directive v/s @Component in Angular could be substituted with something similar to

<contact-card [name]="'foo'" [city]="'bar'" (onClick)="someAction()"></contact-card>

Perchance I didn't understand it properly and it is not possible to substitute it, but it case it is, is there any good reason or useful examples where using @Directive is actually necessary or simpler than tweaking a @Component?

Thanks in advance!

xavier
  • 1,860
  • 4
  • 18
  • 46
  • 1
    Here is a perfect example of a directive: https://angular.io/guide/attribute-directives – Jamie Rees Mar 27 '19 at 11:20
  • Thank you for the example. I had already read it and I have the feeling (I didn't implement it though) that, as I asked, this @Directive could be substituted by an equivalent amount of code. Something like: `

    Highlight me!

    ` but, as I said, I might be wrong. I'll try to do it as an exercise, actually.
    – xavier Mar 27 '19 at 11:33
  • Possible duplicate of [Angular 2 Show and Hide an element](https://stackoverflow.com/questions/35163009/angular-2-show-and-hide-an-element) – Bhagwat Tupe Mar 27 '19 at 13:49
  • In the other question mentioned there is a very interesting application of a Directive, but the other answers show there are other solutions and therefore it does not answer my question. Anyway, I'm having the feeling directives are just a (slightly) different tool which might or might not be used to solve a given problem. – xavier Mar 27 '19 at 14:29

1 Answers1

1

Directives add behaviour to an existing DOM element or an existing component instance.

A component, rather than adding/modifying behaviour, actually creates its own view (hierarchy of DOM elements) with attached behaviour.

Refer the following documentations:

Directive

Component

Seba Cherian
  • 1,755
  • 6
  • 18