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 {}
ありがとうございました!
をありがとう!これは動作します! –
私は 'selector 'と' @Input() 'に同じ名前を使うよう提案しました。 – AngularChef
これは非常に役に立ちます。ありがとうございました! –