角度2を学習しようとする角度1のベテランです。私は自分自身とそのサブコンポーネントに注入される状態サービス(以下、MyState
)を持つコンポーネントを持っています。私は次のように、トップレベルのコンポーネントで別のメンバーを更新し、サービスの状態の変更を監視したい:注入されたサービスのプロパティの検出を角度2で変更します。
import { Component, Input } from '@angular/core';
class Item {
constructor(public name: string) {}
}
class MyState {
selectedItems: Item[] = [];
addItem(item: Item) {
this.selectedItems.push(item);
}
}
// subcomponent
@Component({
selector: '[item]',
template: `
<!-- state changed from subcomponent: -->
<button (click)="state.addItem(model)">
select item {{model.name}}
</button>
`
})
class ItemComponent {
@Input() model: Item;
constructor(private state: MyState){}
}
// main component
@Component({
selector: 'items',
template: `
<h1> Available Items: </h1>
<ul>
<li *ngFor="let item of items" item [model]="item"></li>
</ul>
<h1> Added Items: </h1>
<p>{{ addedItemsString }}</p>
`,
providers: [MyState],
directives: [ItemComponent]
})
class ListComponent {
@Input() items: Item[];
private addedItemsString: string = '';
constructor(private state: MyState) {
// listen for changes to this.state.selectedItems to
// call this.updateAddedItemsString
}
updateAddedItemsString() {
this.addItemsString = this.state.selectedItems.map(i => i.name).join(', ');
}
}
私の質問は:どのように私はListComponentコンストラクタで擬似コードを実装する必要がありますか?確かに
は、addItemsString
メンバーは不自然であると確かにテンプレート自体で行われますが、私の質問のためにupdateAddedItemsString
がListComponent
の別のメンバーを更新し、より多くの複雑なものを行うことができることを前提とすることができます。
ありがとうございます!
サービスで観測可能なものを使用して、変更をサブスクライブすることができます。 https://angular.io/docs/ts/latest/cookbook/component-communication.html –
リード@GünterZöchbauerに感謝します!フォローアップの質問:Observableを州自体の財産として作成することは賢明ですか? –
AndyPerlitch