简体   繁体   中英

Why @Output doesn't emit anything (in angular 8)

I'm trying to transfer an object to a pot component via @Output.

But emit doesn't return anything and when you put it in the log it's undefined.

This is my code:

Transmitter component :

@Output() menubuttonclicked = new EventEmitter<object>();
.
.
.
clickedmenu(id: string) {
    this.rclickemit.buttonid = id ;
    this.menubuttonclicked.emit(this.rclickemit);
  }

Transmitter html:

<button *ngFor ="let button of Setting.menu" (click)="clickedmenu(button.id)" mat-menu-item>
    <mat-icon>{{button.icon}}</mat-icon>
    <span>{{button.name}}</span>
  </button>

Recipient Component:

ngOnChanges(changes: SimpleChanges): void {
    if (changes['emit']) {
      console.log(this.emit);
    }
  }

But nothing can be printed on the console. I gave the emit variable to get the output but no value in it. Does anyone know the problem?

Update

Recipient Component:

<app-ir-graph-d3  [node]="nodes" [link]="links" [Setting]="Setting" (menubuttonclicked)="emit"></app-ir-graph-d3>

Output event emitter is used as an attribute with parentheses. For example:

In your recipient template:

<app-transmitter-component (menubuttonclicked)="onMenuButtonClicked($event)"></app-transmitter-component>

In your recipient component:

onMenuButtonClicked = (buttonID) => {
   console.log(buttonID)
}

For further reading: https://angular.io/guide/component-interaction

ngOnChanges is called when a change happend at data-bound properties such as @Input properties.

OnChange: https://angular.io/api/core/OnChanges

You need to handle of Output . Let me show an example:

yourOutputComponent.ts:

export class yourOutputComponent implements OnInit {
  @Output() change = new EventEmitter();

  onClick(){
    this.change.emit({newValue: 'I am your data' });
  }
}

and subscribed component fooComponent.html :

<yourOutput (change)="hello($event)"></yourOutput>

fooComponent.ts:

export class fooComponent implements OnInit {
    hello(event:any) {
        console.log(event);
    }
}

You should listen to the changes in the html of the Recipient Component not the ngOnChanges

<recipient-component (menubuttonclicked)='clickHandler($event)'></recipient-component>

Then in the typescript file, you declare teh clickHandler function and receive the input there.

Wherever in the Transmitting component you have used Recipient Component Please write eventEmmiter variable, and listen that event in the Recipient Component.

<Recipient Component (menubuttonclicked) = "matButtonClicked($event)">

Recipient Component

matButtonClicked(event) {
 console.log(event) // 'this.rclickemit'
}

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