将一个数值从一个组件发送到 Angular2 中的另一个组件 [英] Send a number value from one component to another component in Angular2

查看:24
本文介绍了将一个数值从一个组件发送到 Angular2 中的另一个组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我进行了搜索,但未能将其集成到我的项目中.
**问题:**我必须将一个包含数字的变量从 component.ts 发送到 component.ts .注意:我不希望该值出现在 HTML 页面中.下面我给出了一个示例,我想要数据!


I had searched but failed to integrate then in my project.
**Problem:**I have to send a variable contains number,to a component.ts from component.ts . Note: I don't want that value in HTML page. Below i have given a sample example,how i want the data!!

child.component.ts
===================
export class Child{

x:number;
<!-- may be some code to send the x value-->
<!-- Remember the value is in a method,which is onclick of a button-->

  onButtonClick(){

   x=5;

  }
}

parent.component.ts
====================
export class parent{

<!--some code goes here to get the x value-->

console.log("The value of x from Child: ",x);

}

现在就像上面的代码一样,我想要组件中 x 的值并在控制台中显示该值.
谢谢你的好主意.

Now as like above code,i want the value of x in the component and show that value in the console.
Thanks for brilliant idea.

推荐答案

将我的示例应用到您提供的代码中....

Adopting my example to your provided code....

import { Parent } from './locationofparent'


@Component({selector: 'child'})
export class Child{

 constructor(private parent: Parent) {  }

 x:number;
  <!-- may be some code to send the x value // just need to have the parent read it-->
  <!-- Remember the value is in a method,which is onclick of a button-->

  ngOnInit() { 
     this.parent.addChild(this);
  }

  onButtonClick(){

   this.x=5;

  }

}

================================

================================

import { Child } from './locationofchild'

@Component({selector: 'child' })
export class Parent{

   constructor()  { }

   child: Child;

    addChild(myChild: Child) {
       this.child = myChild;
    }

   someOtherMethod(){   
       console.log(this.child.x)  <--- will print 5, assuming 5 has been set by the click, otherwise it will print undefined
   }
}

这篇关于将一个数值从一个组件发送到 Angular2 中的另一个组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆