何时使用Angular Directives,Components&模组 [英] When to use Angular Directives, Components & Modules

查看:69
本文介绍了何时使用Angular Directives,Components&模组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读文档,但是对于何时应该使用指令或组件似乎还是很困惑……

此外,什么时候最好抽象出组件并将它们放入模块中?

解决方案

实际上,根据角度文档,组件也是一种指令.

Angular中有三种指令:

  1.组件-带有模板的指令.2.结构化指令-通过添加和删除DOM元素来更改DOM布局.3.属性指令-更改元素的外观或行为,组件或其他指令. 

当您的要求是创建一组可重复使用的html元素时,请使用 components .例如,如果需要制作CRUD屏幕,则可以创建一个组件,该组件包括表格,保存,编辑,删除按钮等.角度屏幕也是一个组件,也可以由多个组件构成.

如果您的要求是轻松更改现有组件或元素的样式或结构,则可以使用指令.考虑一下* ngFor,它是一个结构指令,用于构造一组元素.您还可以使用指令为现有组件提供其他功能.例如,您可以创建一个指令,该指令为表组件提供过滤或导出支持.

此外,什么时候最好提取组件并将其放入模块?

将组件等放置到不同的模块中完全是关于模块化.这样,您可以将彼此相关的事物进行分组,并在需要时通过将其导入来重复使用它们.例如,当您需要http调用时,可以导入http-client-module,该模块包含一个http客户端和相关内容.模块的另一个好处是,您可以通过延迟加载模块来减小应用程序的初始大小,这意味着,如果将组件放入延迟加载的模块中,则仅在需要时(必须使用/显示在屏幕上)下载该模块

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

解决方案

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

这篇关于何时使用Angular Directives,Components&模组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆