title: ‘[Note of Angular 2] How to pass variable between two components’
情境 I:
有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
在
AComponent.ts的class中先宣告myVar1
2
3
4
5export class AComponent implements OnInit {
myVar: number;
...
...
}在
AComponent.html傳入變數1
<B-selector [myVar]="myVar"></B-selector>
在
BComponent.ts中 importInput功能,並宣告變數,變數前面需要加上@Input()1
2
3
4
5
6import { Component, Input, OnInit } from '@angular/core';
...
export class BComponent implements OnInit {
@Input() myVar: number;
}接著就可以在B Component中使用該變數了
參考
情境 II:
接續上例,在B Component更動過該變數之後,想要讓A Component同時也發生變化。
在
AComponent.ts的class中先宣告一個函數來處理B component更動到myVar的事件1
2
3
4
5
6
7
8export class AComponent implements OnInit {
myVar: any;
...
...
onChangeVar(variable: number) {
this.myVar = variable;
}
}在
AComponent.html中bind該事件1
<B-selector [myVar]="myVar" (onChangeVar)="onChangeVar($event)"></B-selector>
在
BComponent.ts中 importOutput、EventEmitter功能,並宣告在1提到的函數,變數前面需要加上@Output()1
2
3
4
5
6
7
8import { Component, Input, OnInit } from '@angular/core';
...
export class BComponent implements OnInit {
...
@Output() onChangeVar = new EventEmitter();
...
}接著就可以在B Component中使用該函數來傳回更新過後的值
1
this.onChangeVar.emit(newVar);
參考
情境 III:
想要直接在 A Component中操作 B Component 的變數與函式
理論上父元件無法讀取子元件的變數也無法使用子元件的函式,但是我們在templete中可以藉由參考變數(reference variable)來使用子元件的變數與函式。
假設
BComponent.ts有一個變數counter與兩個函式add()、minus()1
2
3
4
5
6
7
8
9export class BComponent implements OnInit {
counter: number = 0;
add() {
this.counter += 1;
}
minus() {
this.counter -= 1;
}
}在
BComponent.html中顯示counter這變數1
<h1>{{counter}}</h1> in B Component
現在要在
AComponent.html中使用add()與minus()來操作counter,首先要在<B-selector>中加入一個#開頭的參考變數。1
<B-selector #myCounter></B-selector>
然後就可以在透過
myCounter來使用BComponent的函式與變數1
2
3
4<h2>{{myCounter.counter}}</h2> in A Component <br>
<button (click)="myCounter.add()">+1</button>
<button (click)="myCounter.minus()">-1</button>
<B-selector #myCounter></B-selector>結果如圖所示,上半段為A Component,可以使用兩個按鈕來操作B component的中變數

參考