【问题标题】:Send value from Child Component to Parent, let the parent modify and pass it back to child将值从子组件发送到父组件,让父组件修改并将其传递回子组件
【发布时间】:2017-12-01 21:20:42
【问题描述】:

请在此处查看示例 https://stackblitz.com/edit/angular-dybb4v

  sendValueToParentForModification(e) {
//Send the value to parent
this.sendValue.emit({ childComponent: this, e: e, myValue: this.myValue });
/*
The parent modifies the value and that modified value should be used here.. 
Right now, I'm having the parent component call the function in this child "useModifiedValue".
Instead, I want the flow to somehow come over here.. so that I can call the 
"useModifiedValue" function right here, with the modified value. How to do this?
*/

}

基本上,我想将一个值发送到父组件,让父根据需要修改它,然后在子组件中 - 我想使用修改后的值。

我不想在父组件中添加另一个“发射”。有什么方法可以链接值流?

感谢您的帮助。

【问题讨论】:

  • 尝试理解场景的快速问题:如果您想要孩子的价值,为什么它会去父母并返回?他们俩都更改值似乎不是一个好习惯。如果只有父级更改它只是从父级发送值并在子级上创建一个@Input()。
  • 父组件可以根据需要进行更改。这就是为什么它必须去父母那里,然后再回到孩子身上。基本上 - Child ----> 使用数据向 Parent 发出事件 Parent --> 如果需要,修改它 -->> Child 使用修改后的数据。我的问题是捕获孩子中父母修改的数据。像这样.. childComponent.emit({data}).done { /* 使用修改后的值*/}

标签: angular


【解决方案1】:

您可以实现一个服务来充当两者之间的“中间人”。在两个组件中导入服务,当一个组件更改服务中的变量时,它会反映在另一个组件中。除了一次之外不需要发出任何东西,并使用 OnInit() 订阅父子节点。

【讨论】:

  • Brandon - 谢谢...你有机会演示这种方法吗?
【解决方案2】:

尝试以下方法:

// Parent component
@Component({
  selector: 'parent-component',
  template: '<child-component (valueChanged)="changeValue($event)" [childValue]="childValue"></childComponent>'
})
export class ParentComponent {
  childValue: 'hello world';

  changeChildValue(newValue){
    this.childValue = newValue;
  };
}

// Child component

@Component({
  selector: 'child-component',
  template: '<div>{{childValue}}</div>'
})
export class ChildComponent {
  @Input() childValue;
  @Output() valueChanged = new EventEmmiter<any>();

  changeValue(newValue) {
    valueChanged.emit(newValue);
  }
}

从父组件传递 childValue 作为输入。

根据您的逻辑,更改子项内部的 childValue,然后使用新值调用 changeValue 方法。父组件将接收该事件并更新在子组件上自动更新的值

【讨论】:

    猜你喜欢
    • 2020-02-04
    • 2020-07-30
    • 1970-01-01
    • 2019-01-04
    • 2018-04-16
    • 2019-01-21
    • 2020-10-17
    • 2019-02-27
    • 2017-04-20
    相关资源
    最近更新 更多