2017-01-27 6 views
1

入力数値を表示して表示する指示文を作成する方法。重要な部分は、変更を検出して入力値の変化に対応するための指示です。ここで角2:数値データの色付けと表示の指示

は私のサンプルコードです:

//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

ありがとうございました!

答えて

2

ngOnInit()メソッドではなく、ディレクティブのngOnChanges()メソッド内でスタイルを更新するコードを配置します。

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

ADDITIONAL改善を参照してください。selector@Input()に同じ名前を使用しないのはなぜ?

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

今、あなたは(よりコンパクトに)このようなあなたのディレクティブを使用することができます。

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

をありがとう!これは動作します! –

+0

私は 'selector 'と' @Input() 'に同じ名前を使うよう提案しました。 – AngularChef

+0

これは非常に役に立ちます。ありがとうございました! –

関連する問題