Angular のコンポーネント間の値の受け渡し方法

Angularでのコンポーネント間値渡しには、いくつかの方法があります。

  1. @Inputと@Outputデコレータを利用:@Inputデコレータを使って親コンポーネントから渡された値を子コンポーネントで受け取り、@Outputデコレータを使って子コンポーネントの値を親コンポーネントに渡す。
  2. 親コンポーネント:
  3. import { Component } from ‘@angular/core’;@Component({
    selector: ‘app-parent’,
    template: `

    親コンポーネント

    `
    })
    export class ParentComponent {
    parentValue: string;

    handleChildEvent(event: string) {
    console.log(event);
    }
    }

  4. 子コンポーネント:
  5. @Component({
    selector: ‘app-child’,
    template: `

    子コンポーネント


    `
    })
    export class ChildComponent {
    @Input() childValue: string;
    @Output() childEvent = new EventEmitter();
    }

  6. サービスを利用する:共通のサービスを作成し、渡したい値をそこに保持し、値にアクセスしたいコンポーネントにそのサービスを注入する
  7. 共有サービス
  8. import {Injectable} from ‘@angular/core’;@Injectable({
    providedIn: ‘root’
    })
    export class SharedService {
    sharedValue: string;
    }
  9. コンポーネント 1
  10. import { Component } から `@angular/core` までをネイティブの日本語に言い換えます。import { Component } from ‘@angular/core’;
    => import { Component } from ‘@angular/core’;
  11. コンポーネント 2:
  12. 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) {}
    }

  13. 各コンポーネントは、URL にパラメータを渡すことでルーティングパラメータを介してやり取りできます。
  14. ルーティングの設定:
  15. 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 { }

  16. コンポーネント 1
  17. 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’];
    });
    }
    }

  18. コンポーネント 2
  19. 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’];
    });
    }
    }

これらの方法はすべて、コンポーネント間の値渡しを実現できます。どの方法を選択するかは、

bannerAds