📜  Angular 7指令

📅  最后修改于: 2020-12-16 05:06:24             🧑  作者: Mango

Angular 7指令

指令是DOM中的指令。它们指定如何在Angular中放置组件和业务逻辑。

指令是js类,并声明为@directive。 Angular中有3个指令。

  • 组件指令
  • 结构指令
  • 属性指令

组件指令:组件指令在主类中使用。它们包含有关如何在运行时处理,实例化和使用组件的详细信息。

结构指令:结构指令以*符号开头。这些指令用于操纵和更改DOM元素的结构。例如,* ngIf和* ngFor。

属性指令:属性指令用于更改DOM元素的外观和行为。例如:ngClass,ngStyle等。

属性指令和结构指令之间的区别

Attribute Directives Structural Directives
Attribute directives look like a normal HTML Attribute and mainly used in databinding and event binding. Structural Directives start with a * symbol and look different.
Attribute Directives affect only the element they are added to. Structural Directives affect the whole area in the 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为我设置样式

My Servers



  • {{ server }}

Style me with your created SimpleStyleDirective

Output:

Angular 7 Directives

You can see that your created attribute directive is working. Here, you have learnt how to create selector, how to create attribute directory, and also learnt how to use and also how to use






Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA