![](/img/trans.png)
[英]How to pass value from one component to another component in Angular2?
[英]How to pass variable value from one component to another in Angular2
我正在使用Angular4和angular-cli重建一個舊的Web平台(用php編碼)。
我正在尋找一種在名為my-configuration的組件中聲明多個變量一次的方法,以便我可以直接在其他組件中使用它們,例如my-footer,而無需重新聲明它們:
我-configuration.component.ts
import {Component} from '@angular/core';
@Component ({
selector: 'my-configuration',
templateUrl: './my-configuration.component.html',
styleUrls: ['./my-configuration.component.css']
})
export class MyConfigurationComponent {
variable1: String;
variable2: String;
constructor(){
this.variable1 = 'value1';
this.variable2 = 'value2';
}
}
我-footer.component.ts
import {Component} from '@angular/core';
@Component ({
selector: 'my-footer',
templateUrl: './my-footer.component.html',
styleUrls: ['./my-footer.component.css']
})
export class MyFooterComponent {
footer-variable1: String;
footer-variable2: String;
constructor(){
this.footer-variable1 = //Get the variable1 value from MyConfigurationComponent;
this.footer-variable1 = //Get the variable2 value from MyConfigurationComponent;
}
}
這樣做的正確方法是什么?
在整個應用程序中共享數據的推薦方法是使用Angular服務。 它們被定義為單例,因此您保留的任何值都可用於整個應用程序。
您可以在此處找到有關服務的更多信息: https : //angular.io/docs/ts/latest/tutorial/toh-pt4.html
我剛剛整理了一篇博文和一篇文章,展示了如何做到這一點:
http://blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/
enter code here
看看環境/ environment.ts,你可以把你的變量放在那里,或者你可以像這樣使用
export const config = {
variable1: 'ble',
variable2: 'bla'
};
如果你的兩個組件有父子關系,你可以使用@ViewChild()或@Output(),否則服務是共享數據的最佳方式。
您可以找到有關組件通信的更多信息https://angular.io/docs/ts/latest/cookbook/component-communication.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.