繁体   English   中英

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

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


我进行了搜索,但后来未能整合到我的项目中。
**问题:**我必须将一个包含数字的变量从component.ts发送到component.ts。 注意:我不需要HTML页面中的该值。 下面我给出了一个示例示例,我如何想要数据!

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值并在控制台中显示该值。
感谢您的好主意。

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

我建议您对这个问题使用反应式编程方法。 您可以在下面的代码中查看实现。

这是作为服务的组件(请记住,使用前需要提供服务)

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

由于我们使用的是反应式编程,因此当服务中x的值更改时,由于我们已经订阅了值更改,因此在父级组件中也将具有更新的值。

这是组件:

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

请记住,Child是服务(而不是组件),需要在@NgModule中提供

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

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

所有这些答案使事情复杂化了。 对于直接的父级->子级或子级->父级通信,您可以简单地使用依赖项注入,这与在实例化组件时通常在构造函数中注入其他Angular类时使用的技术相同。

假设您有一些父项

export class ParentComponent {

   someString: string;

   constructor( )  {} 

   someMethod() {
      return someVal : any;
   }

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

在其任何子级中,您都可以将该父级组件的实例作为参数注入到childcomponents构造函数中。 您只需要像导入其他类一样导入它即可。

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

现在,子级可以使用this.parent.whatever访问父级组件的任何公共方法或属性。

为了与父对象进行通信,可以在父组件中创建一个对象,该对象存储ChildComponent的实例。 因此,类似地,将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);
    } 
}

然后在父组件中添加一些方法,以将其子组件的实例添加到数组中(使用映射可能更好,但是我现在将其简化)。

然后在子级中,您只需在添加子级的父级中调用该方法

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

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

现在,您的孩子可以通过this.parent访问父级的公共属性,而您的父母可以通过this.arrayOfChildren [0]访问其父级的公共属性。 响应式编程很棒,但对于在层次结构上不直接相关的指令/组件之间需要通信时,它非常有用。 有直接关系时,有很多简单的选择。

注意:我选择数组的唯一原因是bc通常,父母有很多后代。 没有理由不能仅仅创建一个名为

myChild: ChildComponent;

并直接将孩子存放在那里。

在提供的代码中采用我的示例...。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM