Angular のコンポーネント間の値の受け渡し方法
Angularでのコンポーネント間値渡しには、いくつかの方法があります。
- @Inputと@Outputデコレータを利用:@Inputデコレータを使って親コンポーネントから渡された値を子コンポーネントで受け取り、@Outputデコレータを使って子コンポーネントの値を親コンポーネントに渡す。
- 親コンポーネント:
- import { Component } from ‘@angular/core’;@Component({
selector: ‘app-parent’,
template: `親コンポーネント
`
})
export class ParentComponent {
parentValue: string;handleChildEvent(event: string) {
console.log(event);
}
} - 子コンポーネント:
- @Component({
selector: ‘app-child’,
template: `子コンポーネント
`
})
export class ChildComponent {
@Input() childValue: string;
@Output() childEvent = new EventEmitter();
} - サービスを利用する:共通のサービスを作成し、渡したい値をそこに保持し、値にアクセスしたいコンポーネントにそのサービスを注入する
- 共有サービス
- import {Injectable} from ‘@angular/core’;@Injectable({
providedIn: ‘root’
})
export class SharedService {
sharedValue: string;
} - コンポーネント 1
- import { Component } から `@angular/core` までをネイティブの日本語に言い換えます。import { Component } from ‘@angular/core’;
=> import { Component } from ‘@angular/core’; - コンポーネント 2:
- import { Component } from ‘@angular/core’;
import { SharedService } from ‘./shared.service’;@Component({
selector: ‘app-component2’,
template: `コンポーネント 2
{{ sharedService.sharedValue }}
`
})
export class Component2Component {
constructor(public sharedService: SharedService) {}
} - 各コンポーネントは、URL にパラメータを渡すことでルーティングパラメータを介してやり取りできます。
- ルーティングの設定:
- import { NgModule } from ‘@angular/core’;
import { Routes, RouterModule } from ‘@angular/router’;
import { 画面1Component } from ‘./画面1.component’;
import { 画面2Component } from ‘./画面2.component’;const routes: Routes = [
{ path: ‘画面1/:値’, component: 画面1Component },
{ path: ‘画面2/:値’, component: 画面2Component },
];@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { } - コンポーネント 1
- import { Component, OnInit } from ‘@angular/core’;
import { ActivatedRoute } from ‘@angular/router’;@Component({
selector: ‘app-sample’,
template: `サンプル
値: {{ value }}
`
})
export class SampleComponent implements OnInit {
value: string;constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route.params.subscribe(params => {
this.value = params[‘value’];
});
}
} - コンポーネント 2
- import { Component, OnInit } from ‘@angular/core’;
import { ActivatedRoute } from ‘@angular/router’;@Component({
selector: ‘app-component2’,
template: `Component 2
値: {{ value }}
`
})
export class Component2Component implements OnInit {
value: string;constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route.params.subscribe(params => {
this.value = params[‘value’];
});
}
}
これらの方法はすべて、コンポーネント間の値渡しを実現できます。どの方法を選択するかは、