When to use Angular Directives, Components & Modules

天大地大妈咪最大 提交于 2020-11-28 19:47:50

问题


I've been reading the documentation but still seem to be confused on when you should use a directive or a component...

Also, when is it best to abstract components and place them into modules??


回答1:


In fact, a component is also a type of directive according to the angular docs.

There are three kinds of directives in Angular:

1. Components—directives with a template.
2. Structural directives—change the DOM layout by adding and removing DOM elements.
3. Attribute directives—change the appearance or behavior of an element,
   component, or another directive.

You use components, when your requirement is to create a reusable group of html elements. For example, if your requirement is to make a CRUD screen you create a component and it includes a table, save, edit, delete buttons and so on. An angular screen also is a component or can be constructed from multiple components.

If your requirement is to easily change the style or the structure of an existing component or an element you use directives. Think about *ngFor, it is a structural directive and it is used to structure a group of elements. You can also use directives to provide additional features to existing components. For example you can create a directive that provides filtering or exporting support to a table component.

Also, when is it best to abstract components and place them into modules??

Placing components etc. into different modules is all about modularity. In this way you can group things that's relavant with each other and reuse them by importing them when they are needed. You import http-client-module when you require http calls for example, that module contains an http client and related stuff. One other benefit of modules is you can decreise your application's initial size by lazy loading your modules which means if you put your component in a lazy loaded module it is only downloaded when it is needed (must be used/ shown) in the screen



来源:https://stackoverflow.com/questions/56047247/when-to-use-angular-directives-components-modules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!