Introduction
Directives are classes that add additional behavior to elements in your Angular applications.
Angular has many kinds of directives, including components, attribute directives, and structural directives.
Component
This is the most common one we used every day, a component is a directive with a template. Components are the most basic building block of an Angular application.
https://angular.dev/guide/components
Structural Directives
Structural directives are responsible for HTML layout. They shape or reshape the DOM’s structure, typically by adding, removing, or manipulating elements.
NgIf
NgIf
is used to conditionally creates or disposes of subviews in a template. see this post for more details.
NgFor
NgSwitch
Angular17引入了新的控制流语句:@if
, @for
, @switch
,这些语句可以替代NgIf, NgFor, NgSwitch,更加简洁,高效,我们建议使用新的控制流语句。
Attribute Directives
Attribute directives are used to change the appearance or behavior of an element, component, or another directive. They are usually applied to elements as attributes.
Attribute directives doesn’t change the layout of the template, just change the appearance of it, for example, change the color, font size, visibility etc.
The most common attribute directives are as follows:
NgClass
NgStyle
NgModel
Customize Directives
如果内置的Directive不能满足我们的需求,我们可以自定义Directive,下面我们自定义一个Directive来实现一个简单Hover变色功能,当鼠标移动到元素上时,元素背景色变为红色,鼠标移出时恢复原背景色。
Create a directive
使用以下命令创建一个新的指令:HoverDirective
,该命令会创建文件src/app/hover.directive.ts
。
1 | ng g d hover |
Implement the directive
以下是该指令的实现代码:
1 | import {Directive, ElementRef, HostListener} from '@angular/core'; |
简单解释一下上述代码:
- selector:
appHover
,这个是Directive的名字,我们在HTML中使用这个名字来引用这个Directive。 - constructor中注入了
ElementRef
,这个是Angular提供的一个服务,用来获取当前元素的引用。这里的当前元素就是使用了该Directive的元素。 - 两个HostListener分别监听
mouseenter
和mouseleave
事件,当鼠标移入时,设置背景色为红色,移出时恢复原色。
Use the directive
首先,在需要使用这个指令的组件或者模块中的imports
数组中导入这个Directive。
1 | imports: [HoverDirective], |
然后,在需要使用这个Directive的元素上加上appHover
属性即可(注意:appHover
就是定义Directive时指定的selector
)。此时,当鼠标移入时,该段落的背景色会变为红色,移出时恢复原背景色。
1 | <p appHover>Hover me</p> |
这个自定义指令非常简单,虽然现在可以工作,但是有一个缺点,就是颜色的变化是固定的,如果我想让用户自定义Hover时的颜色,该怎么办呢?这就涉及到如何给自定义指令传递参数了。
我们修改一下实现,将颜色作为参数传递给Directive,这里我们定义了一个@Input属性,用来接收参数。@Input属性的名字是appHover
,所以这里appHover
同时作为Directive的selector和Input属性的名字。
1 | // Add an input property to the directive |
另外,为了防止用户忘记传递参数,我们给hoverColor设置了一个默认值'red'
,这样即使用户不传递参数,也不会报错。
现在,我们可以在HTML中传递颜色参数了。
1 | <p appHover="green">Hover me</p> |
上面的例子只有一个参数,所以我们在定义@Input
的时候,直接把参数定义到了Directive的selector上,如果有多个参数,这种方法就不好使了,为了说明问题,我们再加一个参数,字体颜色,就是当鼠标Hover时改变背景色,同时也改变字体颜色。
1 | import {Directive, ElementRef, HostListener, Input} from '@angular/core'; |
使用时:
1 | <p appHover hoverFontColor="red" hoverBackgroundColor="yellow">This is a paragraph</p> |