【问题标题】:Nested Child Component not passing Info to Parent Component嵌套子组件未将信息传递给父组件
【发布时间】:2019-08-09 07:20:25
【问题描述】:

我正在学习如何在父组件和子组件之间传递信息。我了解信息是通过@Inputs 和@Outputs 传递的。

例如,我有一个父类实例化一个名为

的基本字符串变量
test: string;

并为其分配一个随机字符串,如

  ngOnInit() {
    this.test = "message from parent";
   }

我使用@Input 将这个变量传递给几个嵌套的子类,并在我的最后一个子类的console.log(test) 中成功返回从父类接收到的值。但是,当我在子类中更改它时,真正的问题就开始了。在我的子班中,我有一个功能:

@Output() testChange: EventEmitter<any> = new EventEmitter();

newSpecifier(){
    this.test= "this changed"
    this.testChange.emit(this.test)

  }

还有一个按钮来触发这个功能。但是,当我单击按钮时,父“测试”没有任何反应。我在原始父 HTML 中有一个具有 {{this.test}} 值的 div,但是当我单击按钮时它不会改变。我认为我的信息没有正确地传递回父组件。任何帮助我指出正确的方向都会很棒,在此先感谢!

【问题讨论】:

  • 你能提供一个sn-p吗,我不知道问题所在。

标签: angular


【解决方案1】:

当您从子组件发出一些事件时,父组件需要有某种方式来“监听”这些事件。在父子动态中,您必须在父组件内部实现的事件侦听器方法支持此机制。让我们看看你的情况。

child.component.ts:

@Output() testChange: EventEmitter<any> = new EventEmitter();

newSpecifier(){
    this.test= "this changed"
    this.testChange.emit(this.test)
}

parent.component.html:

<div>
    <child-component (testChange)="onTestChangeEventHandler($event)"> </child-component>
</div>

parent.component.ts:

onTestChangeEventHandler(event) {
     // here you can do whatever you want with emmited value from child component
     console.log(event);
}

你可以在这里阅读更多:https://angular.io/guide/component-interaction

【讨论】:

    【解决方案2】:
    you need to listen to the emitted changes in your parent component. Below is an example on how you can achieve what you are trying to do
    
    Parent-HTML
    <parent-component>
       <child-component (testchange)="onTestChange($event)></child-component>
    </parent-component>
    
    In Parent--ts file
     ------------------
        onTestChange(event)
        {
          this.test=event
        }
    

    【讨论】:

      【解决方案3】:

      在您的子组件中将输出更改为@Input() myVariable: string。然后在您的父级 .html 文件或父级“html 模板”中渲染子组件,只需通过属性绑定传入值即可。所以你父母的 HTML 代码看起来像这样

      `
      <child-component [myVariable]="this.test"></child-component>
      `
      

      这会将值从父级传递给子级。

      【讨论】:

        猜你喜欢
        • 2020-08-21
        • 2018-10-25
        • 2019-10-19
        • 1970-01-01
        • 2020-09-01
        • 2018-06-17
        • 2023-03-30
        • 2020-02-04
        • 2018-08-03
        相关资源
        最近更新 更多