AngualrJs2官方方法是以@Input,@Output来实现组件间的相互传值,并且组件之间必须父子关系,下面给你们提供一个简单的方法,实现组件间的传值,不单单是父子组件,跨模块的组件也能够实现传值css
/** *1.定义一个服务,做为传递参数的媒介 */ @Injectable() export class PrepService{ //定义一个属性,做为组件之间的传递参数,也能够是一个对象或方法 profileInfo: any; }
/** *2.传递参数的组件,我这边简单演示,直接就在构造器里面实现传参了 */ @Component({ selector: 'XXXXXXX', templateUrl:"./XXXXXX.html", styleUrls:["./XXXXXXX.css"] }) export class ReportComponent { //定义要传递的参数(此处是一个对象,也能够是方法) reponsePrep:any ={ name : "腊肉豆皮", address:"中欧五花肉" } //构造器注入PrepService服务 constructor(private ps:PrepService){ //把当前组件参数赋值给PrepService的profileInfo属性 ps.profileInfo = this.reponsePrep; } }
/** *3.接受参数的组件 */ @Component({ selector: 'YYYYYY', templateUrl:"./YYYYYYYY.html", styleUrls:["./YYYYYYY.css"] }) export class commandComponent { //定义参来接收来自PrepService服务profileInfo属性的值 requestPrep:any; //构造器注入PrepService服务 constructor(private ps:PrepService){ //把PrepService的profileInfo属性的值赋值给requestPrep实现组件的之间的传值 this.requestPrep = ps.profileInfo; } }
思路:定义一个服务做为传递参数的媒介注入在要传参的组件的构造器里面,而后对服务里面属性(传参媒介)来赋值和取值实现组件之间的传参。html
这样就牛逼了,任何组件之间均可以通讯了,仅供参考,本人也是ng2菜鸟。this