首页 文章

将值从子组件发送到父组件,让父组件修改并将其传递回子组件

提问于
浏览
0

请在此处查看示例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?
*/

}

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

我不想在父组件中添加另一个“emit”..有什么方法可以链接值的流量?

谢谢您的帮助 .

2 回答

  • 0

    你可以实现一项服务,充当两者之间的“中间人” . 在两个组件中导入服务,当更改服务中的变量时,它将反映在另一个组件中 . 除了一次之外,不需要发出任何内容,并使用OnInit()在父级和子级中进行订阅 .

  • 0

    请尝试以下方法:

    // 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方法 . 父组件将接收该事件并更新在子项上自动更新的值

相关问题