コンポーネント間でデータを共有する
親子でもなんでもないコンポーネント間でデータを共有したい場合、サービスを利用します。
ディレクトリ、ファイルの構成
今回、試してみたディレクトリ、ファイルの構成は以下の通りです。
project ├ node_modules └ src └ app ├ app.module.ts ├ app.state.ts └ example ├ example1.component.ts └ example2.component.ts
今回は「app.state.ts」で共有するデータを定義しておき、「example1.component.ts」と「example2.component.ts」のコンポーネントで「app.state.ts」で定義しておいたデータの参照または設定を行います。
コード
データ共有に関係ないコードは省略しています。
app.state.ts
import { Injectable } from '@angular/core';
@Injectable()
export class AppState {
public exampleFlag: boolean = false;
}
app.module.ts
import { NgModule } from '@angular/core';
import { AppState } from './app.state';
@NgModule({
...
providers: [
AppState
],
...
})
export class AppModule { }
「providers」についてはこちら(Angular2のDIを知る - Qiita)を参照するとよさげです。
example1.component.ts
import { Component } from '@angular/core';
import { AppState } from '../app.state'
@Component({
selector: 'example1',
styles: [``],
template: `
<div *ngIf="appState.exampleFlag">フラグON<div>
<div *ngIf="!appState.exampleFlag">フラグOFF<div>
<button (click)="changeFlag()">フラグ切替<button>
`,
})
export class Example1Component {
constructor(
private appState: AppState
) { }
changeFlag(): void{
this.appState.exampleFlag = !this.appState.exampleFlag;
}
}
example2.component.ts
import { Component } from '@angular/core';
import { AppState } from '../app.state'
@Component({
selector: 'example2',
styles: [``],
template: `
<div *ngIf="appState.exampleFlag">フラグON<div>
<div *ngIf="!appState.exampleFlag">フラグOFF<div>
`,
})
export class Example2Component {
constructor(
private appState: AppState
) { }
}
上記のようなサービス(AppState)を使うことで、example1のコンポーネントで変更したフラグの状態をexample2のコンポーネントでも参照でき、コンポーネント間でデータの共有が可能になります。