Angular教程

Angular 指令

指令是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
用创建的SimpleStyleDirective设置我的风格
输出:
Angular 7指令
您可以看到您创建的属性指令正在运行。在这里,您学习了如何创建选择器,如何创建属性目录,还学习了如何使用以及如何使用

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4