嵌套子组件未将信息传递给父组件

时间:2019-03-18 20:30:10

标签: angular

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

例如,我有一个父类,该类实例化了一个称为$ p的基本字符串变量。

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,但是当我单击按钮时它不会改变。我认为我的信息无法正确传递回父组件。谢谢,向我指明正确方向的任何帮助都将非常有用!

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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
    }

答案 2 :(得分:0)

在子组件中

将输出更改为@Input() myVariable: string。然后,在呈现子组件的父级.html文件或父级“ html模板”中,只需通过属性绑定传入值即可。因此您父母中的HTML代码如下所示:

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

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

相关问题