close

參考資料:

http://ben-do.github.io/2016/07/22/Note-of-Angular-2-How-to-pass-variable-between-two-components/

https://angular.io/guide/component-interaction

 

有A B兩個component,B為A的child component,想要在B component 顯示 A component的變數。

檔案分別有以下四個,其對應到的selector分為別<A-selector><B-selector>,要傳的變數為myVar

  • AComponent.ts
  • AComponent.html
  • BComponent.ts
  • BComponent.html
  1. AComponent.ts的class中先宣告myVar

    1
    2
    3
    4
    5
    export class AComponent implements OnInit {
    myVar: number;
    ...
    ...
    }
  2. AComponent.html傳入變數

    1
    <B-selector [myVar]="myVar"></B-selector>
  3. BComponent.ts中 import Input功能,並宣告變數,變數前面需要加上@Input()

    1
    2
    3
    4
    5
    6
    import { Component, Input, OnInit } from '@angular/core';
    ...

    export class BComponent implements OnInit {
    @Input() myVar: number;
    }
  4. 接著就可以在B Component中使用該變數了

參考


情境 II:

接續上例,在B Component更動過該變數之後,想要讓A Component同時也發生變化。

  1. AComponent.ts的class中先宣告一個函數來處理B component更動到myVar的事件

    1
    2
    3
    4
    5
    6
    7
    8
    export class AComponent implements OnInit {
    myVar: any;
    ...
    ...
    onChangeVar(variable: number) {
    this.myVar = variable;
    }
    }
  2. AComponent.html中bind該事件

    1
    <B-selector [myVar]="myVar" (onChangeVar)="onChangeVar($event)"></B-selector>
  3. BComponent.ts中 import OutputEventEmitter功能,並宣告在1提到的函數,變數前面需要加上@Output()

    1
    2
    3
    4
    5
    6
    7
    8
    import { Component, Input, OnInit } from '@angular/core';
    ...

    export class BComponent implements OnInit {
    ...
    @Output() onChangeVar = new EventEmitter();
    ...
    }
  4. 接著就可以在B Component中使用該函數來傳回更新過後的值

    1
    this.onChangeVar.emit(newVar);

 

 

 

arrow
arrow
    全站熱搜
    創作者介紹

    Chill_Radio 發表在 痞客邦 留言(0) 人氣()