Angular2組件間數據傳遞有多種方式,其中最常用的有兩種,一種是配置元數據(或者標簽裝飾),一種是用單例模塊傳遞;有兩個元數據具有傳遞數據的功能:inputs和outputs。
一、元數據傳遞
1)配置inputs,接收外部傳來的參數:
在inputs里配置輸入屬性,宿主同過這個屬性就能把數據傳進來。
示例如下:
@Component({ selector: 'test-component', template: `{{inputValue}}`, inputs: ['inputsValue'] }) export class TestComponent { private inputsValue;//注意,要在組建內聲明,才能使用 }
宿主通過“[輸入屬性]=輸入值”的方式傳值,給屬性打上中括號代表輸入。以上面例子為例,其父組件調用方式如下:
@Component({ selector: 'parent-component', template: `<test-component [inputsValue]="data"></test-component>`//以“[屬性]=值”的方式傳遞 }) export class ParentComponent { private data = 'Hello InputValue~!'; }
當然,如果不配置元數據,我們還可以在組件類中用“@Inputs() inputsValue”聲明,效果一樣;我們還可以編寫“setter”函數對輸入的數據進行加工過濾,這里不做細講。
2)配置outputs,給父組件傳遞數據:
outputs是利用自定義事件的機制給父組件傳遞數據;元數據配置與inputs相似,只是組件類中要給輸出屬性創建EventEmitter實例。
示例如下:
@Component({ selector: 'test-component', template: `<button (click)="clickToSend()">點擊按鈕,輸出數據</button>`, outputs: '[outputValue]' }) export class TestComponent { public outputValue = new EventEmmitter; private clickToSend() { this.outputValue.emit('Hello OutputValue~!');//注意,自定義事件必須要借助異步程序執行發布函數;異步程序有事件、前后端數據交互、延時函數。 } }
outputs相當於給組件聲明了一個自定義事件,父組件綁定該事件就能與輸出機制建立聯系,輸出數據就是事件對象。
以上面例子為例,父組件示例如下:
@Component({ selector: 'parent-component', template: `<test-component (outputValue)="getValue($event)"></test-component>`//屬性加上小括號代表輸出 }) export class ParentComponent { private getValue(event) { console.log(event);//Hello OutputValue~! } }
同樣,你也可以用@Output來聲明,這里不做細講。
二、單例模塊傳遞
JavaScript傳值策略是:基本類型數據傳數據副本,對象類型數據傳對象引用。Angular2各模塊注入Module中,只要在Module作用域范圍,這些模塊再通過依賴注入方式注入到別的模塊,依賴的模塊是單例的。
我們可以利用對象傳引用的特性,達到組件間傳遞數據的目的。
比如我想將數據傳給子組件,只需在子組件構造器中注入該組件,該組件由於是單例的,那么一方改動另一方能實時訪問到。
示例如下:
//父組件: @Component({ selector: 'parent-component', template: ` <p>{{value}}</p> <child-component></child-component> ` }) export class ParentComponent { public value = 'Parent Value...';//注意!這里不能使用private權限,否則外部模塊無法訪問到這個屬性。 } //子組件: @Component({ selector: 'child-component', template: `{{_parent.value}}` }) export class ChildComponent { constructor(private _parent: ParentComponent) {}//注入父組件的實例,就能訪問到父組件非私有屬性了。 }
結果是<p>Parent Value...</p><child-component>Parent Value...</child-component>
你還可以用指令、管道、服務來傳值,只要是單例模塊,都能做到;不過為了代碼內聚性,建議只使用組件或者服務作為值傳遞的媒介。
還有別的傳值方式嗎?
當然還有,比如繞過Angular2的API,使用JQuery的data函數進行值的獲取和傳遞。不建議這么做,Angular不鼓勵開發者直接操作DOM,它內置了一系列指令以及機制來弱化開發者對DOM的直接操作,開發者使用Angular提供的API可以減少很多操作DOM的代碼。