简体   繁体   中英

Angular 7: passing parameters to other component error

I have 2 components, one parent and one child, I would like to send the value of a variable to the parent component, I tried the code below but without succeed. The child component is sent the information correctly, but the parent is not receiving, looks like the function in the parent component is not identifying the receiving of the data to be triggered.

child component

...

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
  }

parent component

...

constructor() {

}

ngOnInit() {

}

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

Parent template

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

Thanks.

Inside parentheses you should put the name of the property that is decorated with @Output decorator. In this case (element)

Change your parent.html to this:

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

In your parent component you need to bind to correct event from your child component.

In your child component you declared Output() called element so in this case the correct event name to use in the parent component will be element

Correct code will be:

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

Official Angular Documentation - Component Interaction

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM