【问题标题】:Angular Directive角度指令
【发布时间】:2016-05-05 01:59:59
【问题描述】:

是否有人使用@Directive decorator 创建了任何示例 Angular Directive?我搜索了很多,但是到目前为止所有开发人员都创建了组件指令。甚至 Angular API Review 也没有对此多说。

【问题讨论】:

标签: angular angular2-directives


【解决方案1】:

Simple-Directive-Demo这是一个从 angular2 指令开始的非常简单的示例

我有一个组件和指令。

我使用指令来更新组件的视图。此外,指令的 changeColor 函数组件的 changeColor 函数调用。

组件

@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({

  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;
     }

 }

【讨论】:

    【解决方案2】:

    简单来说 Component Directive 将是您的模板指令,我们在构建应用程序时经常使用它 -> 在您的 html 中 -> &lt;custom-tag&gt;&lt;/custom-tag&gt;

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

    结构指令是通过删除添加元素来修改 DOM 的指令。 示例是

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

    ngIf 如果为 true 则添加 div 否则如果更改为 false 则删除。

    最后是属性指令,名字说明了一切......它是一个“基于属性的指令” 例如:

    <input type="text" pPassword />
    
    @Directive({
        selector: '[pPassword]'
    })
    

    【讨论】:

      【解决方案3】:

      Angular 指令分为三种:

      Components
      Attribute directives
      Structural directives
      

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

      Angular2 指导结构指令代码:https://github.com/guyoung/GyPractice-Angular2/tree/master/apps/structural-directives

      【讨论】:

        【解决方案4】:

        这是一个示例指令。这会为在组件外部完成的点击添加一个事件侦听器。

        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);
            }
          }
        }
        

        可以这样使用:

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

        只要有人在app-comp之外点击,就会触发close

        【讨论】:

          【解决方案5】:

          根据 Angular2 文档,指令用于更改 DOM 元素的行为。

          让我们创建一个指令,在 mouseenter 的情况下将 div 的背景色更改为红色,在 mouseleave 的情况下将其更改为黄色。

          第 1 步:创建组件

          import {Component} from '@angular/core';
          
          @Component({
            selector: 'my-comp',
            template: '<div colorFlip>This is just a Demo!</div>'
          })
          
          export class MyComp {}
          

          第 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;
            }
          } 
          

          第 3 步:注册指令

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

          【讨论】:

            猜你喜欢
            • 2018-04-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-04-01
            • 2014-03-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多