简体   繁体   English

将数值从一个组件发送到Angular2中的另一个组件

[英]Send a number value from one component to another component in Angular2


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 . **问题:**我必须将一个包含数字的变量从component.ts发送到component.ts。 Note: I don't want that value in HTML page. 注意:我不需要HTML页面中的该值。 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);

}

Now as like above code,i want the value of x in the component and show that value in the console. 现在就像上面的代码一样,我想要组件中的x值并在控制台中显示该值。
Thanks for brilliant idea. 感谢您的好主意。

Use Output & EventEmitter properties. 使用Output & EventEmitter属性。

// parent.component.ts
// ==================== 

export class parent{
    updateValue(newValue: any){
        console.log("The value of x from Child: ", newValue);
    }
}

// parent.component.html
// ====================

<child (childValue)="updateValue($event)"></child>

// child.component.ts
// ===================

import { Output, EventEmitter } from '@angular/core';

export class Child{
    @Output() childValue: EventEmitter<any> = new EventEmitter();
    onButtonClick(){
        this.childValue.emit('value here');
    }
}

I would suggest you use the reactive programming approach for this issue. 我建议您对这个问题使用反应式编程方法。 You can see the implementation in the code below. 您可以在下面的代码中查看实现。

Here is the Child component as service (keep in mind that services need to be provided before usage) . 这是作为服务的组件(请记住,使用前需要提供服务)

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class ChildService {
    public x$: Observable<string>;
    private x: BehaviorSubject<string>;

    constructor() {
        this.x = new BehaviorSubject<string>(null);
        this.x$ = this.x.asObservable();
    }
}

Since we are using reactive programming, when the value of x in the Child service changes, we will have the updated value in the Parent component as well because we are subscribed to the value changes. 由于我们使用的是反应式编程,因此当服务中x的值更改时,由于我们已经订阅了值更改,因此在父级组件中也将具有更新的值。

Here is the Parent component: 这是组件:

import { Component } from '@angular/core';

import { ChildService } from './child.service';

@Component({
    selector: 'app-parent',
    templateUrl: './parent.component.html',
    styleUrls: ['./parent.component.css']
})
export class ParentComponent {
    x: string;

    constructor(childService: ChildService) {
        childService.x$.subscribe((value: string) => {
            this.x = value;
        });
    }
}

Keep in mind that Child is a service (and not component) and needs to be provided in an @NgModule 请记住,Child是服务(而不是组件),需要在@NgModule中提供

import { ChildService } from './child.service';

@NgModule({
    // ....
    providers: [
        ChildService
    ]
    // ....
})
export class AppModule { }

All of these answers overcomplicate things. 所有这些答案使事情复杂化了。 For direct parent -> child or child -> parent communication, you can simply use dependency injection, the same technique you may often use to inject other Angular classes in constructors when components are instantiated. 对于直接的父级->子级或子级->父级通信,您可以简单地使用依赖项注入,这与在实例化组件时通常在构造函数中注入其他Angular类时使用的技术相同。

Lets say you have some parent component 假设您有一些父项

export class ParentComponent {

   someString: string;

   constructor( )  {} 

   someMethod() {
      return someVal : any;
   }

   private somePrivateMethod() {  return 'cant touch this'  }
}

In any of its children, you can inject the instance of that parent component as a parameter in the childcomponents constructor. 在其任何子级中,您都可以将该父级组件的实例作为参数注入到childcomponents构造函数中。 You just need to import it like you do other classes. 您只需要像导入其他类一样导入它即可。

import { ParentComponent } from './wherever/parent/is/'

export class ChildComponent { 

   constructor(private parent:ParentComponent) { }

   ngOnInit() {
      let abc = this.parent.someMethod(); // works bc method is public
      let nope = this.parent.somePrivateMethod(); // will throw a compile error
    }
}

Any public methods or properties of the parent component will now be accessible in by the child using this.parent.whatever. 现在,子级可以使用this.parent.whatever访问父级组件的任何公共方法或属性。

For communication back to the parent, you can create an object in the parent component that stores instances of the ChildComponent. 为了与父对象进行通信,可以在父组件中创建一个对象,该对象存储ChildComponent的实例。 So similarly, import the ChildComponent into the ParentComponent file. 因此,类似地,将ChildComponent导入ParentComponent文件。

import { ChildComponent } from './wherever/child/is'

export class ParentComponent {

   someString: string;
   someNum: number;
   arrayOfChildren: ChildComponent[] = [];

   constructor( )  {} 

   someMethod() {
       return someVal : any;
   }

   addChild( child: ChildComponent ) {
      this.arrayOfChildren.push(child);
    } 
}

And then add some method in the parent component that adds instances of its child components to an array (probably better to use a map, but I'm keeping it simple for now). 然后在父组件中添加一些方法,以将其子组件的实例添加到数组中(使用映射可能更好,但是我现在将其简化)。

Then in the child, you just call that method in the parent that adds children 然后在子级中,您只需在添加子级的父级中调用该方法

export class ChildComponent { 
   constructor(private parent:ParentComponent) { }

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

Now your child can access public properties of parent via this.parent, and your parent can access public properties of its children via this.arrayOfChildren[0]. 现在,您的孩子可以通过this.parent访问父级的公共属性,而您的父母可以通过this.arrayOfChildren [0]访问其父级的公共属性。 Reactive programming is great, but its great for when communication is required between directives / components that aren't directly hierarchially related. 响应式编程很棒,但对于在层次结构上不直接相关的指令/组件之间需要通信时,它非常有用。 There are much simpler options when you have direct relationships. 有直接关系时,有很多简单的选择。

Note: the only reason I chose an array is bc typically parents have many descendants. 注意:我选择数组的唯一原因是bc通常,父母有很多后代。 There's no reason you couldn't just create a property called 没有理由不能仅仅创建一个名为

myChild: ChildComponent;

and store the child directly to that. 并直接将孩子存放在那里。

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
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在angular2中需要将数据从一个组件发送到另一组件 - In angular2 need to send data from one component to another component 如何在Angular2中将值从一个组件传递到另一个组件? - How to pass value from one component to another component in Angular2? 如何在Angular2中将变量值从一个组件传递到另一个组件 - How to pass variable value from one component to another in Angular2 如何通过服务将数据从Angular2中的一个组件发送到另一个组件 - How to send data from one component to another component in Angular2 through service 如何从另一个组件调用一个组件中的方法是 angular2 - how to call a method in one component from another component is angular2 Angular2从另一个组件调用一个函数组件 - Angular2 call one function component from another component Angular2-在另一个组件中更改组件值 - Angular2 - Change Component value in another component Angular2:将数据从一个组件发送到另一个组件并处理该数据 - Angular2: Send data from one component to other and act with the data 如何将值从一个组件发送到另一个组件? - How to send a value from one component to another? 如何在angular2中将数组的索引从一个组件传递到另一个组件? - How to pass index of an array from one component to another in angular2?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM