Send a number value from one component to another component in Angular2

那年仲夏 提交于 2019-12-10 12:04:36

问题



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);

}

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.


回答1:


Use Output & EventEmitter properties.

// 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');
    }
}



回答2:


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.

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

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

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



回答3:


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.

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

For communication back to the parent, you can create an object in the parent component that stores instances of the ChildComponent. So similarly, import the ChildComponent into the ParentComponent file.

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]. 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. There's no reason you couldn't just create a property called

myChild: ChildComponent;

and store the child directly to that.




回答4:


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


来源:https://stackoverflow.com/questions/45832929/send-a-number-value-from-one-component-to-another-component-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!