11

This question already has an answer here:

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...


1 답변


18

You can think of any Component as a Directive with a View.

Consequences

Based on the fact that only components have views, there are a couple of consequences, for instance:

  • Only components may define directives to be used in the component itself and the entire subtree it is root of.
  • Only components may define pipes to be used in the component and the entire subtree it is root of.
  • Only components can define viewEncapsulation since they can have views, in contrast to directives
  • When the framework creates an ElementInjector for given component, it'll be marked as a Host injector.
  • A separate instance of the change detector is going to be created only for components (and respectively only components can define change detection strategy).

Further details

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.

Linked


Related

Latest