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中使用它。 我们还将创建自己的自定义指令。 那么,我们还等什么呢? 让我们深入了解它。
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 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 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 NgSwitch.
通过查看语法,您可以轻松地区分结构指令和属性指令。 结构指令的名称始终以星号(*)开头,而属性指令不包含任何前缀。 Angular提供的三种最受欢迎的内置结构指令是NgIf , NgFor和NgSwitch 。
Components are directives with templates. The only difference between Components and the other two types of directives is the Template. Attribute and Structural Directives don't have Templates. So, we can say that the Component is a cleaner version of the Directive with a template, which is easier to use.
组件是带有模板的指令。 组件和其他两种类型的指令之间的唯一区别是模板。 属性和结构指令没有模板。 因此,可以说该组件是带有模板的指令的较干净版本,更易于使用。
There are a lot of built-in Directives available in Angular which you can easily use. In this section, we will use two very simple built-in directives.
Angular中有很多内置指令,您可以轻松使用它们。 在本节中,我们将使用两个非常简单的内置指令。
NgStyle Directive is an Attribute directive used to change the styling of any DOM element on the basis of some condition.
NgStyle指令是一个Attribute指令,用于根据某些条件更改任何DOM元素的样式。
I am an Attribute Directive
In the above code snippet, we are adding a blue background if the value of
isBlue
variable is true. If the value ofisBlue
variable is false, then the background of the above element will be red.在上面的代码片段中,如果
isBlue
变量的值为true,则添加蓝色背景。 如果isBlue
变量的值为false,则上述元素的背景将为红色。
NgIf Directive is a structural directive used to add elements into the DOM according to some condition.
NgIf指令是一种结构指令,用于根据某些条件将元素添加到DOM中。
I am a Structural Directive
In the above code snippet, the whole paragraph will remain in the DOM if the value of
show
variable is true, else it will kick off from the DOM.在上面的代码片段中,如果
show
变量的值为true,则整个段落将保留在DOM中,否则将从DOM开始。
Creating a custom directive is just like creating an Angular component. To create a custom directive we have to replace @Component
decorator with @Directive
decorator.
创建自定义指令就像创建Angular组件一样。 要创建自定义指令,我们必须将@Component
装饰器替换为@Directive
装饰器。
So, let's get started with creating our first Custom Attribute directive. In this directive, we are going to highlight the selected DOM element by setting an element’s background color.
因此,让我们开始创建第一个Custom Attribute指令。 在此指令中,我们将通过设置元素的背景色来突出显示所选的DOM元素。
Create an app-highlight.directive.ts
file in src/app
folder and add the code snippet below.
在src/app
文件夹中创建一个app-highlight.directive.ts
文件,并在下面添加代码段。
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private eleRef: ElementRef) {
eleRef.nativeElement.style.background = 'red';
}
}
Here, we are importing Directive
and ElementRef
from Angular core. The Directive
provides the functionality of @Directive
decorator in which we provide its property selector to appHighLight
so that we can use this selector anywhere in the application. We are also importing the ElementRef
which is responsible for accessing the DOM element.
在这里,我们从Angular核心导入Directive
和ElementRef
。 Directive
提供@Directive
装饰器的功能,其中我们将其属性选择器提供给appHighLight
以便我们可以在应用程序中的任何位置使用此选择器。 我们还将导入负责访问DOM元素的ElementRef
。
Now to get appHighlight
Directive to work, we need to add our Directive to the declarations array in the app.module.ts
file.
现在, appHighlight
指令appHighlight
,我们需要将指令添加到app.module.ts
文件中的声明数组中。
import ...;
import { ChangeThemeDirective } from './app-highlight.directive';
@NgModule({
declarations: [
AppComponent,
ChangeThemeDirective
],
imports: [
...
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Now we are going to use our newly created custom directive. I am adding the appHightlight
directive in the app.component.html
but you can use it anywhere in the application.
现在,我们将使用新创建的自定义指令。 我加入appHightlight
的指令app.component.html
,但你可以在任何地方应用程序使用它。
Highlight Me !
The output of the above code snippet will look like this.
上面的代码片段的输出将如下所示。
In the previous section, we created our first Attribute directive. The same approach is used to create the structural directive as well.
在上一节中,我们创建了第一个Attribute指令。 同样的方法也用于创建结构指令。
So, let’s get started with creating our structural directive. In this directive, we are going to implement the *appNot
directive which will work just opposite of *ngIf
.
因此,让我们开始创建结构指令。 在此指令中,我们将实现*appNot
指令,该指令将与*ngIf
相反。
Now create a app-not.directive.ts
file in the src/app
folder and add the code below.
现在,在src/app
文件夹中创建一个app-not.directive.ts
文件,并添加以下代码。
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[appNot]'
})
export class AppNotDirective {
constructor(
private templateRef: TemplateRef,
private viewContainer: ViewContainerRef) { }
@Input() set appNot(condition: boolean) {
if (!condition) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear(); }
}
}
As you saw in the above code snippet, we are importing Directive, Input, TemplateRef and ViewContainerRef
from @angular/core.
如您在上面的代码片段中所看到的,我们正在从@angular/core.
导入Directive, Input, TemplateRef and ViewContainerRef
@angular/core.
Directive
provides the same functionality for the @Directive
decorator. The Input
decorator is used to communicate between the two components. It sends data from one component to the other using property binding.
Directive
为@Directive
装饰器提供相同的功能。 Input
装饰器用于在两个组件之间进行通信。 它使用属性绑定将数据从一个组件发送到另一个组件。
TemplateRef
represents the embedded template which is used to instantiate the embedded views. These embedded views are linked to the template which is to be rendered.
TemplateRef
表示用于实例化嵌入式视图的嵌入式模板。 这些嵌入的视图链接到要渲染的模板。
ViewContainerRef
is a container where one or more views can be attached. We can use createEmbeddedView()
function to attach the embedded templates in the container.
ViewContainerRef
是一个可以附加一个或多个视图的容器。 我们可以使用createEmbeddedView()
函数将嵌入式模板附加到容器中。
Now to get the appNot
directive to work, we need to add our directive to the declarations array in the app.module.ts
file.
现在, appNot
指令起作用,我们需要将指令添加到app.module.ts
文件中的声明数组。
import ...;
import { AppNotDirective } from './app-not.directive';
@NgModule({
declarations: [
AppComponent,
AppNotDirective
],
imports: [
...
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Now, it’s time to use our newly created structural directive.
现在,该使用我们新创建的结构指令了。
I am adding the appNot
directive in the app.component.html
but you can use it anywhere in the application.
我加入appNot
的指令app.component.html
,但你可以在任何地方应用程序使用它。
True
False
The *appNot
directive is designed in a way that it appends the template element into the DOM if the *appNot
value is false
just opposite the *ngIf
directive.
*appNot
指令的设计方式是,如果*appNot
值为false
, *ngIf
与*ngIf
指令相对的模板元素添加到DOM中。
The output of the above code snippet will look like this.
上面的代码片段的输出将如下所示。
I hope this article answered most of your questions regarding Angular directives. If you have any queries or doubts, feel free to reach out to me in the comment box.
我希望本文能够回答您有关Angular指令的大多数问题。 如果您有任何疑问或疑问,请随时在评论框中与我联系。
翻译自: https://www.freecodecamp.org/news/angular-directives-learn-how-to-use-or-create-custom-directives-in-angular-c9b133c24442/
angular 自定义指令