Angular 7:将参数传递给其他组件错误

时间:2019-02-22 13:43:15

标签: javascript angular typescript events components

我有2个组件,一个父对象和一个孩子,我想将变量的值发送给父组件,我尝试了下面的代码,但没有成功。子组件已正确发送信息,但父组件未接收到信息,看起来父组件中的功能无法识别要触发的数据的接收。

子组件

...

private elements:any;
@Output() element = new EventEmitter<any>();


 constructor() {

 }

  ngOnInit() {
    this.sendContent();
  }


 sendContent() {
    this.elements = "hi";

    console.log("sended");
    console.log(this.elements);

    this.element.emit(this.elements);
    //the function is activated and I can see the return in the console
  }

父组件

...

constructor() {

}

ngOnInit() {

}

receiveContent(elements) {
    console.log("received");
    console.log(elements);
    //the function is not activated when the child component is sent the data
 }

父模板

<app-child (sendContent)="receiveContent($event)"></app-child>

谢谢。

2 个答案:

答案 0 :(得分:3)

您应该在括号内放置使用@Output装饰器装饰的属性的名称。在这种情况下(元素)

将您的parent.html更改为此:

<app-child (element)="receiveContent($event)"></app-child>

答案 1 :(得分:0)

在父组件中,您需要绑定到子组件中的正确事件。

在子组件中,您声明了名为Output()的{​​{1}},因此在这种情况下,要在父组件中使用的正确element名称将是event

正确的代码将是:

element

Official Angular Documentation - Component Interaction