mahdi aghasi
mahdi aghasi

Reputation: 378

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>

Upvotes: 1

Views: 3617

Answers (4)

StepUp
StepUp

Reputation: 38124

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);
    }
}

Upvotes: 2

aditya agnihotri
aditya agnihotri

Reputation: 36

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'
}

Upvotes: 0

Ayman El Temsahi
Ayman El Temsahi

Reputation: 2610

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.

Upvotes: 0

Harun Yilmaz
Harun Yilmaz

Reputation: 8558

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

Upvotes: 3

Related Questions