EventEmitter
APIと@Output
デコレータを使用する必要があります。
// app.component.ts
import {Component} from 'angular2/core';
import {CounterComponent} from './counter.component';
@Component({
selector: 'my-app',
styles: [`
.app {
display: block;
text-align: center;
padding: 25px;
background: #f5f5f5;
}
`],
template: `
<div class="app">
<counter [counterValue]="myValue"></counter>
</div>
`,
directives: [CounterComponent]
})
export class AppComponent {
public myValue:number = 2;
myValueChange(event) {
console.log(event);
}
}
クラスAppComponent
で私たちが宣言した:
のは、私たちは親Component
とセットアップ我々はCounterComponent’s
と呼ばれるコンポーネントにバインドするとき呼び出したいクラスにmyValueChangeと呼ばれる機能を持っていると仮定しましょうmyValueChange
は、イベントを引数として受け取ります。次は、カスタムを作成する必要があるのはcounterChange
それを呼びましょう、にこの機能をフックする<counter>
コンポーネントに属性名:私たちはそれを括弧で囲んで(counterChange)
を使用しましたか
// app.component.ts
import {Component} from 'angular2/core';
import {CounterComponent} from './counter.component';
@Component({
selector: 'my-app',
styles: [`
.app {
display: block;
text-align: center;
padding: 25px;
background: #f5f5f5;
}
`],
template: `
<div class="app">
<counter [counterValue]="myValue" (counterChange)="myValueChange($event);"></counter>
</div>
`,
directives: [CounterComponent]
})
export class AppComponent {
public myValue:number = 2;
myValueChange(event) {
console.log(event);
}
}
注、これはこれであると角度伝えますイベントバインディングは、(click)
に似ています。今度は、このAPIをCounterComponent
の内部でミラーリングする必要があります。
// counter.component.ts
import {Component, Input, Output, EventEmitter} from 'angular2/core';
@Component({
selector: 'counter',
styles: [`
// omitted
`],
template: `
// omitted
`
})
export class CounterComponent {
@Input() counterValue = 0;
@Output() counterChange = new EventEmitter();
increment() {
this.counterValue++;
this.counterChange.emit({
value: this.counterValue
})
}
decrement() {
this.counterValue--;
this.counterChange.emit({
value: this.counterValue
})
}
}
@Output
counterChangeがEventEmitter
の新しいインスタンスに設定されている方法に注意してください、この@Output
デコレータは、我々は上記のテンプレート(counterChange)
で見てきたように結合イベントとしてcounterChange
プロパティが利用できるようになります。
ほとんどの場合、子コンポーネントComponent
が実際に値を更新したときに、counterChange
イベントが発生したことを親コンポーネントに伝えたいと思います。それはそうする論理的な場所だとのは、そこにイベントを放出してみましょう:とき、それは立派に見えますが、我々は値のプロパティでObject
を放出している
// counter.component.ts
...
export class CounterComponent {
@Input() counterValue = 0;
@Output() counterChange = new EventEmitter();
increment() {
this.counterValue++;
this.counterChange.emit({
value: this.counterValue
})
}
decrement() {
this.counterValue--;
this.counterChange.emit({
value: this.counterValue
})
}
}
注意、あなたはこれを行う必要はありません。親のコールバックでイベントを使用します(より明示的なevent.value)。
親コンポーネントは$event
オブジェクトをフェッチすることができます。(counterChange)="myValueChange($event);"
を使用してテンプレートに渡しました。
// app.component.ts
...
export class AppComponent {
public myValue:number = 2;
myValueChange(event) {
// result: { value: <number> }
console.log(event);
}
}
これだけです。
Angular2はangularjsではありません。タグを修正してください。また、サービスを利用する。サブジェクト(typescriptの場合)を作成し、それを介してシグナルを送信します。 –