Angular 2:着色和显示数字数据的指令

时间:2017-01-27 11:18:25

标签: angular angular2-changedetection

如何创建用于着色和显示输入数值的指令。重要的部分是检测变化并对输入值变化做出反应的指令。

这是我的示例代码:

//our root app component
import {Directive, Component, NgModule, Input, OnInit, OnDestroy, ElementRef} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <h2>Random number: <span my-value [value]="num"></span></h2>
    </div>
  `,
})
export class App implements OnInit, OnDestroy {
  name: string;
  num: number = 100;

  private interval: any;

  constructor() {
    this.name = 'Angular2';

  }

  ngOnInit() {
    this.interval = setInterval(() => {
       this.num = this.getRandomInt(-100, 100);
    }, 1000);
  }

  ngOnDestroy {
      clearInterval(this.interval);
  }

  private getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }
}


@Directive ({
  selector: '[my-value]'
})
export class MyValueDirective {
  @Input() value: number;

  constructor(private el: ElementRef) {

  }

  ngOnInit(): void {
     if (this.value < 0) {
      this.el.nativeElement.style.color = 'red';
     } else {
      this.el.nativeElement.style.color = 'blue';
     }
     this.el.nativeElement.innerHTML = this.value;
  }
}


@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App, MyValueDirective ],
  bootstrap: [ App ]
})
export class AppModule {}

Example code in Plunker

谢谢!

1 个答案:

答案 0 :(得分:3)

将更新样式的代码放在指令的ngOnChanges()方法中,而不是ngOnInit()方法。

Angular在检测到指令的输入属性发生更改时调用ngOnChanges()方法。见https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#onchanges

@Directive ({
  selector: '[my-value]'
})
export class MyValueDirective {
  @Input() value: number;

  constructor(private el: ElementRef) {}

  ngOnChanges(changes: SimpleChanges) {
     const value = changes['value'];
     if (value < 0) {
       this.el.nativeElement.style.color = 'red';
     } else {
       this.el.nativeElement.style.color = 'blue';
     }
     this.el.nativeElement.innerHTML = value;
  }
}

其他改进:为什么不对selector@Input()使用相同的名称?

@Directive ({
  selector: '[myValue]'
})
export class MyValueDirective {
  @Input() myValue: number;
  // ...
}

现在你可以像这样使用你的指令(更紧凑):

<span [myValue]="num"></span>