本文概述
指令是DOM中的指令。它们指定了如何在Angular中放置组件和业务逻辑。
指令是js类,并声明为@directive。 Angular中有3个指令。
- 组件指令
- 结构指令
- 属性指令
组件指令:组件指令在主类中使用。它们包含有关在运行时如何处理,实例化和使用组件的详细信息。
结构指令:结构指令以*符号开头。这些指令用于操纵和更改DOM元素的结构。例如,* ngIf和* ngFor。
属性指令:属性指令用于更改DOM元素的外观和行为。例如:ngClass,ngStyle等。
属性指令和结构指令之间的区别
属性指令 | 结构指令 |
---|---|
属性指令看起来像一个普通的HTML属性,主要用于数据绑定和事件绑定。 | 结构指令以*符号开头, 外观有所不同。 |
属性指令只影响它们被添加到的元素。 | 结构指令影响DOM中的整个区域。 |
如何创建自定义指令?
你可以创建自己的自定义指令以在Angular组件中使用。
创建一个基本的属性指令
你已经看到了ngClass和ngStyle等属性指令。现在,该创建我们自己的属性指令了。
首先,创建一个文件夹。让我们将其命名为“简单样式”。然后,在该文件夹中创建一个名为“ simple-style.directive.ts”的文件
import {Directive, ElementRef, OnInit} from '@angular/core';
@Directive( {
selector: '[appSimpleStyle]'
})
export class SimpleStyleDirective implements OnInit {
constructor(private elementRef: ElementRef) {
}
ngOnInit() {
this.elementRef.nativeElement.style.backgroundColor = 'green';
}
现在,你必须通知Angular你有一个新指令。因此,你必须将SimpleStyleDirective添加到app.module.ts并同时将其导入。
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {SimpleStyleDirective} from './simple-style/simple-style.directive';
@NgModule({
declarations: [
AppComponent, SimpleStyleDirective
], imports: [
BrowserModule
], providers: [], bootstrap: [AppComponent]
})
export class AppModule { }
现在,你的指令已创建。让我们检查一下。打开app.component.html并使用你创建的SimpleStyleDirective
<p appSimpleStyle>使用你创建的SimpleStyleDirective为我设置样式</ p>
<div class="container">
<div class="row">
<div class="col-xs-12">
<h2>My Servers</h2>
<button class="btn btn-primary" (click)="OnAddServer()">Add Server</button>
<br><br>
<ul class="list-group">
<li
class="list-group-item "
*ngFor="let server of servers; let i = index"
(click)="onRemoveServer(i)">{{ server }}
</li>
</ul>
<p appSimpleStyle>Style me with your created SimpleStyleDirective</p>
</div>
</div>
</div>
</textarea></div>