Home > OS >  EventEmiter from child to parent not working
EventEmiter from child to parent not working

Time:03-23

I need to pass a value (0) to a parent component, so I call a child component as follows:

<app-componentadduser [target]="target" *ngIf="opt==1" (newItemEvent)="changeOpt($event)"></app-componentadduser>

And the code for changeOpt:

changeOpt(newItem: number) {
    console.log(newItem)
    this.opt = newItem;
  }

On the child side,

@Input() target: string;
  @Output() newItemEvent = new EventEmitter<number>();

Then when a button is clicked, and after a process takes place:

this.newItemEvent.emit(0);

From the parent, I even try to console.log newItem (value is 0) but changeOpt is never executed.

I dont know what Im missing. I thought the *ngIf had something to do with it, but it doesn't.

Thanks.

UPDATE:

Console.log is throwing this error:

TypeError: ctx_r9.changeOpt is not a function. (In 'ctx_r9.changeOpt($event)', 'ctx_r9.changeOpt' is undefined)

CodePudding user response:

Since you are just passing a number, try

(newItemEvent)="opt=$event"

CodePudding user response:

first of all i do not know where do you call the this.newItemEvent.emit(0);

So its possible that there is problem with this method. You should call it for example on button or on some action. Everything else seems fine, but maybe i am blind :D

Anyway i created stackBlitz example with your output and everything works. Have a look.

example

  • Related