简体   繁体   English

角度指令

[英]Angular Directive

has anyone created any sample Angular Directive using @Directive decorator ?有没有人使用@Directive装饰器创建过任何示例Angular 指令 I searched a lot on however all developers so far created component directives.我搜索了很多但是到目前为止所有开发人员都创建了组件指令。 Even Angular API Review doesn't speak more on this.甚至Angular API Review也没有对此进行更多说明。

Simple-Directive-Demo .简单指令演示 This is a very simple example to start with angular2 directive .这是一个从 angular2 指令开始的非常简单的例子

I have a component and directive.我有一个组件和指令。

I use directive to update component's view.我使用指令来更新组件的视图。 Moreover directive's changeColor function is getting called with a component's changeColor function .此外,指令的 changeColor 函数组件的 changeColor 函数调用

Component成分

@Component({
  selector: 'my-app',
  host: {'[style.backgroundColor]':'color',}
  template: `
      <input type="text" [(ngModel)]="color" (blur)="changeColor(color)" />
      <br>
      <span > (span) I'm {{color}} color <span>
      <div mySelectedColor [selectedColor]="color"> (div) I'm {{color}} color </div>
    `,
    directives: [selectedColorDirective]
})

export class AppComponent implements AfterViewInit{
  @ViewChild(selectedColorDirective) myDirective: selectedColorDirective;
  color:string;
  constructor(el:ElementRef,renderer:Renderer) {
    this.color="Yellow";
    //renderer.setElementStyle(el, 'backgroundColor', this.color);
  }
  changeColor(color)
  {
    this.myDirective.changeColor(this.color);
  }
  ngAfterViewInit() { }
 }

Directive指示

@Directive({

  selector:"[mySelectedColor]", 
    host: {
   // '(keyup)': 'changeColor()',
   // '[style.color]': 'selectedColor',
  }

  })

  export class selectedColorDirective { 

    @Input() selectedColor: string = ''; 

    constructor(el: ElementRef, renderer: Renderer) {
      this.el=el;
        this.el.nativeElement.style.backgroundColor = 'pink'; 
      // renderer.setElementStyle(el, 'backgroundColor', this.selectedColor);
    } 

    changeColor(clr)
    {
     console.log('changeColor called ' + clr);
     //console.log(this.el.nativeElement);
     this.el.nativeElement.style.backgroundColor = clr;
     }

 }

In Simple Terms Component Directive will be your directives with template which we use a lot while building a app -> in your html -> <custom-tag></custom-tag>简单来说,组件指令将是您的模板指令,我们在构建应用程序时经常使用它 -> 在您的 html -> <custom-tag></custom-tag>

@Component({
selector : 'custom-tag',
template : '<p> My Custom Tag</p>'
})

Structural Directive are the ones that modify the DOM, by removing adding elements.结构指令是通过删除添加元素来修改 DOM 的指令 Example would be例子是

<div *ngIf="showErrorMessage">{{errorMessage}}</div>

ngIf would add the div if true else remove if it changes to false. ngIf 将添加 div 如果为真,否则删除如果它更改为假。

Lastly are the Attribute Directive , the name says it all..its a 'attribute based directive' Example would be :最后是Attribute Directive ,名称说明了一切......它是一个“基于属性的指令”示例将是:

<input type="text" pPassword />

@Directive({
    selector: '[pPassword]'
})

There are three kinds of Angular directives: Angular 指令分为三种:

Components
Attribute directives
Structural directives

Angular2 Guide Attribute Directives Code : https://github.com/guyoung/GyPractice-Angular2/tree/master/apps/attribute-directives Angular2 指南属性指令代码: https : //github.com/guyoung/GyPractice-Angular2/tree/master/apps/attribute-directives

Angular2 Guide Structural Directives Code : https://github.com/guyoung/GyPractice-Angular2/tree/master/apps/structural-directives Angular2 指南结构指令代码: https : //github.com/guyoung/GyPractice-Angular2/tree/master/apps/structural-directives

Here's a sample directive.这是一个示例指令。 This add a event listener for click done outside a component.这为在组件外完成的单击添加了一个事件侦听器。

import {Directive, ElementRef, HostListener, EventEmitter, Output} from '@angular/core';

@Directive({
  selector: '[clickedOutside]'
})
export class ClickedOutsideDirective {
  @Output()
  public clickedOutside = new EventEmitter();

  constructor(private _elemRef: ElementRef) {
  }

  @HostListener('document:click', ['$event'])
  public onClick(event) {
    const targetElement = event.target;
    if (!targetElement) {
      return;
    }
    /**
     * In case the target element which was present inside the referred element
     * is removed from the DOM before this method is called, then clickedInside
     * will be false even if the clicked element was inside the ref Element. So
     * if you don't want this behaviour then use [hidden] instead of *ngIf
     */
    const clickedInside = this._elemRef.nativeElement.contains(targetElement);
    if (!clickedInside && !this._elemRef.nativeElement.isSameNode(targetElement)) {
      return this.clickedOutside.emit(event);
    }
  }
}

This can be used as follows:这可以按如下方式使用:

<app-comp (clickedOutside)='close()'></app-comp>

close will be triggered whenever someone clicks outside app-comp每当有人在app-comp之外点击时就会触发close

As per Angular2 docs, directives are used to change the behaviour of the DOM element.根据 Angular2 文档,指令用于更改 DOM 元素的行为。

Lets create one directive which would change the backgroundcolor of the div to red in case of mouseenter and yellow in case of mouseleave.让我们创建一个指令,它将在 mouseenter 的情况下将 div 的背景颜色更改为红色,在 mouseleave 的情况下将其更改为黄色。

Step 1: Create Component步骤 1:创建组件

import {Component} from '@angular/core';

@Component({
  selector: 'my-comp',
  template: '<div colorFlip>This is just a Demo!</div>'
})

export class MyComp {}

Step 2: Create Directive第 2 步:创建指令

import {Directive, HostListener, ElementRef} from '@angular/core';

@Directive({
  selector: '[colorFlip]'
})

export class ColorFlip {
  constructor(private el: ElementRef) {}
  @HostListener('mouseenter') handleMouseEnter() {
    this.flipColor('red');
  }

  @HostListener('mouseleave') handleMouseEnter() {
    this.flipColor('yellow');
  } 

  flipColor(color:string) {
    this.el.nativeElement.style.backgroundColor = color;
  }
} 

Step 3: Register Directive第 3 步:注册指令

@NgModule({
  imports: [...],
  declarations: [MyComp , ColorFlip ]
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM