Search code examples
angulartypescriptasynchronouseventemitter

Can not emit event from async method in typescript


I have a child component which should emit an event.However i want the parent handler method to be async.It seems that the parent does not receive the emitted object in this case:

Parent Component

<computer-create-modal (onsubmit)="handleCreateAsync($value)"
                       >
          </computer-create-modal>

export class IndexComponent implements OnInit {
async handleCreateAsync(computer:Computer){
    console.log(computer); //always undefined
    if(computer=null && computer.id !=null){

    }

  }
}

Child Component

<input class="form-control" type="text" [(ngModel)]="id" name="id" id="id"/>
<input class="form-control" type="text" [(ngModel)]="username"  name="username" id="name"/>

export class ComputerCreateModalComponent implements OnInit {
  @Output()
  protected onsubmit:EventEmitter<Computer>=new EventEmitter<Computer>();

  protected username:string="";
  protected id:string="";


  async onSubmitAsync(){

          let comp:Computer={
            id:this.id,
            username:this.username
          };
          console.log("from child");
          console.log(comp);
          this.onsubmit.emit(comp);
      }

}

I have tried making the child method that emits the event both sync and async to no avil. Why does my parent not get the value?

P.S I have not added the logic of submit of the child since it does not matter in this case.


Solution

  • This was a silly one.The problem was that i did not follow the convention of using (...)=method($event) and instead wrote $value.

    So the problem was in the parent when binding the handler for the output of the child:

    <computer-create-modal  (onsubmit)="handleCreateAsync($value)"></computer-create-modal>
    

    Changing from $value to $event solved the problem.