I've been struggling to understand what is the difference between these two concepts in the framework.
I'm well familiar with what directives in AngularJS 1.x are and both components and directives in Angular 2 seems quite similar to this concept...
Component is used to break up the application into smaller components. But Directive is used to design re-usable components, which is more behavior-oriented. That is why components are widely used in later versions of Angular to make things easy and build a total component-based model.
Yes, in Angular 2, Components are a type of Directive. According to the Doc, “Angular components are a subset of directives. Unlike directives, components always have a template and only one component can be instantiated per an element in a template.”
A pipe gets data as an input, transforms it and outputs this data in another way. A directive gets a DOM element it's "attached" to and enhances it with some kind of features.
You can think of any Component as a Directive with a View.
Based on the fact that only components have views, there are a couple of consequences, for instance:
directives
to be used in the component itself and the entire subtree it is root of.pipes
to be used in the component and the entire subtree it is root of.viewEncapsulation
since they can have views, in contrast to directivesElementInjector
for given component, it'll be marked as a Host
injector.The classical way of defining component in Angular 2 is:
@Component({
selector: '...',
// ...
})
@View({
template: '...'
})
class ComponentCtrl {...}
The @View
decorator helps you define a view for given component. Initially it was externalized in a separate decorator (just like on the example above) because the Angular team plans to allow a single component to have multiple view definitions (one for each platform the component is going to work on).
Recently this decorator was dropped, so currently you can define a component with:
@Component({
selector: '...',
template: '...',
//...
})
class ComponentCtrl {...}
This way you achieve the same result but with a little bit less of typing. Internally Angular 2 will add the appropriate view metadata based on the properties you've set to the @Component
decorator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With