angular 自定义指令
by Gulfam Ansari
由Gulfam Ansari
After playing with Angular for a long time, I finally came up with an understandable explanation of Angular directives. In this article, we will first understand what a directive exactly is and how to use it in Angular. We will create our own custom directives as well. So what are we waiting for? Let's dive deep into it.
在玩了很长时间的Angular之后,我终于对Angular指令提出了一个可以理解的解释。 在本文中,我们将首先了解什么是确切的指令以及如何在Angular中使用它。 我们还将创建自己的自定义指令。 那么,我们还等什么呢? 让我们深入了解它。
什么是角度指令? (What is an Angular Directive?)
Directives are the functions which will execute whenever Angular compiler finds it. Angular Directives enhance the capability of HTML elements by attaching custom behaviors to the DOM.
指令是只要Angular编译器发现它就会执行的函数。 Angular Directives通过将自定义行为附加到DOM来增强HTML元素的功能。
From the core concept, Angular directives are categorized into three categories.
从核心概念来看,Angular指令可分为三类。
Attribute Directives
属性指令
Structural Directives
结构指令
Components
组件
属性指令 (Attribute Directives)
Attribute Directives are responsible for manipulating the appearance and behavior of DOM elements. We can use attribute directives to change the style of DOM elements. These directives are also used to hide or show particular DOM elements conditionally. Angular provides many built-in Attribute Directives like NgStyle, NgClass, etc. We can also create our own custom Attribute Directives for our desired functionality.
属性指令负责操纵DOM元素的外观和行为。 我们可以使用属性指令来更改DOM元素的样式。 这些指令还用于有条件地隐藏或显示特定的DOM元素。 Angular提供了许多内置的属性指令,例如NgStyle , NgClass等。我们还可以为所需的功能创建自己的自定义属性指令。
结构指令 (Structural Directives)
Structural Directives are responsible for changing the structure of the DOM. They work by adding or removing the elements from the DOM, unlike Attribute Directives which just change the element’s appearance and behavior.
结构指令负责更改DOM的结构。 它们通过在DOM中添加或删除元素来工作,这与仅改变元素外观和行为的“属性指令”不同。
You can easily differentiate between the Structural and Attribute Directive by looking at the syntax. The Structural Directive’s name always starts with an asterisk(*) prefix, whereas Attribute Directive does not contain any prefix. The three most popular built-in Structural Directives Angular provides are NgIf, NgFor, and