【问题标题】:Send a number value from one component to another component in Angular2在Angular2中将一个数字值从一个组件发送到另一个组件
【发布时间】:2017-08-23 07:11:14
【问题描述】:


我已经搜索但未能将其集成到我的项目中。
**问题:**我必须将包含数字的变量从 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 的值并在控制台中显示该值。
谢谢你的好主意。

【问题讨论】:

    标签: angular angularjs-directive


    【解决方案1】:

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

    【讨论】:

    • ,我想知道 必须写成 HTML 还是 .ts 文件?
    • 我不认为,这个,我可以写在 .ts 文件中...我的查询是像上面的代码一样在 .ts 文件中获取 x 值。
    • 这个应该用html写。每当子级发出值时,都会调用父级 .ts 文件中的 updateValue() 函数
    • 你能在下面评论一下在.ts文件中写什么吗?
    【解决方案2】:

    我建议您使用 反应式编程 方法来解决此问题。您可以在下面的代码中看到实现。

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

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

    由于我们使用的是响应式编程,当Child服务中x的值发生变化时,我们会在Parent中得到更新的值> 组件,因为我们订阅了值的变化。

    这是组件:

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

    【讨论】:

    • 如何更改 ChildService 中的变量 x ?
    • @JetersonMirandaGomes 您将需要 ChildService 中的一个方法。像 setX(value: string) { this.x.next(value); }
    【解决方案3】:

    所有这些答案都使事情变得过于复杂。对于直接的父 -> 子或子 -> 父通信,您可以简单地使用依赖注入,当组件被实例化时,您可能经常使用相同的技术在构造函数中注入其他 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] 访问其孩子的公共属性。反应式编程很棒,但它非常适合需要在不直接分层相关的指令/组件之间进行通信。当您有直接关系时,有更简单的选择。

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

    的属性
    myChild: ChildComponent;
    

    并将孩子直接存储到那里。

    【讨论】:

    • 你能解释一下如何在我的代码中写这个。我上面提到过。
    • 我还在等@diopside
    【解决方案4】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-20
      • 2018-02-09
      • 2021-05-02
      • 2020-07-30
      • 2021-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多