代码之家  ›  专栏  ›  技术社区  ›  Mohammad Shadmehr

角度2-将对象从父组件传递到要修改的子组件

  •  0
  • Mohammad Shadmehr  · 技术社区  · 6 年前

    我知道将一个对象从父组件发送到它的子组件就像通过@input发送一样简单。

    实际上,我想把对象的引用发送给子对象,而不是它的值。

    1 回复  |  直到 6 年前
        1
  •  1
  •   HDJEMAI    6 年前

    下面是一个父子通信的示例,我们将在控制台中看到,从父对象传递的子对象的已更改值已更改。

    父组件:

    import { Component, OnChanges, SimpleChanges } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      template: `
        <child [childProp]="parentProp" (childPropChange)="fromChild($event)"></child>
      `
    })
    export class AppComponent implements OnChanges {
      parentProp = {value1: "value1", value2: "value2"};
    
      ngOnChanges(c: SimpleChanges) {
        console.log('Parent changes: This doesnt happen often ', c);
      }
    
      fromChild(val) {
        console.log('Parent: receive from child, ', val.value1);
        console.log('Parent: receive from child, ', val.value2);
        console.log('Parent: receive from child, ', this.parentProp.value1);
        console.log('Parent: receive from child, ', this.parentProp.value2);
      }
    }
    

    子组件:

    import { Component, Input, Output, EventEmitter, OnChanges, SimpleChanges } from '@angular/core';
    
    @Component({
      selector: 'child',
      template: `
        <h3>Child Component with {{childProp}}</h3>
        <button (click)="fire()">Talk to parent</button>
      `
    })
    export class ChildComponent implements OnChanges {
      @Input() childProp;
      @Output() childPropChange = new EventEmitter<{}>();
    
      ngOnChanges(changes: SimpleChanges) {
        console.log('in child changes with: ', changes);
      }
    
      fire() {
        this.childProp.value1 = "value1 changed";
        this.childProp.value2 = "value2 changed";
        this.childPropChange.emit(this.childProp);
      }
    }
    

    This stackblidtz

    在父组件中,我们有以下对象:

    parentProp = {value1: "value1", value2: "value2"};
    

    在子组件中,我们更改从父级接收的对象,并按以下方式发出值:

    this.childProp.value1 = "value1 changed";
    this.childProp.value2 = "value2 changed";
    this.childPropChange.emit(this.childProp);
    

    Parent: receive from child,  value1 changed
    Parent: receive from child,  value2 changed
    Parent: receive from child,  value1 changed
    Parent: receive from child,  value2 changed