首页 文章

角度指令

提问于
浏览
12

有没有人使用 @Directive decorator创建任何样本 Angular Directive ?我搜索了很多,但是到目前为止所有的开发人员都创建了组件指令 . 甚至Angular API Review在这方面也没有多说 .

5 回答

  • 0

    Simple-Directive-Demo . This is a very simple example to start with angular2 directive .

    我有一个组件和指令 .

    我使用指令来更新组件的视图 . 此外 directive's changeColor function 正在调用 component's changeColor function .

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

    简单来说 Component Directive 将是你的模板指令,我们在构建应用程序时使用了很多 - >在你的html中 - > <custom-tag></custom-tag>

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

    Structural Directive 是通过删除添加元素来修改DOM的 . 例子是

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

    ngIf会添加div,如果为true,则删除if,如果它变为false .

    最后是 Attribute Directive ,这个名字说明了一切..例如'attribute based directive'例如:

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

    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

  • 10

    这是一个示例指令 . 这为组件外部的单击完成添加了一个事件监听器 .

    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>
    

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

  • 5

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

    让我们创建一个指令,在mouseenter的情况下将div的backgroundcolor更改为红色,在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 ]
    })
    

相关问题