簡體   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