Home > OS >  Angular EventEmitter parent This equals with the EventEmitter
Angular EventEmitter parent This equals with the EventEmitter

Time:09-13

My problem is when going back to the parent element after EventEmitter trigger my "this" is the EventEmitter itself at the parent, hence I cannot access any methods/variables which are part of the parent. Am I doing something wrong, or it this how it should work?

Maybe the issue comes from the dynamic component? Not sure as I think this is my only different compared to other example where this. seems to be working.

My child component:

@Input() item: someItem;
@Output() newItemEvent = new EventEmitter<any>();

createElement()
  {
    this.newItemEvent.emit(this.item);
  }

HTML:

<form >
    <mat-form-field >
      <input matInput placeholder="Name"  name="name" type="name"  [(ngModel)]="item.name">
    </mat-form-field>

    <div >
      <button mat-raised-button color="primary" type="submit" (click)="createElement()">Create</button>
    </div>
</form>

Parent:


  //create the structure element
  create (element)
  {
    //do something
    this.myMethod(element); 
   }

HTML

<ndc-dynamic 
  [ndcDynamicInputs]="{item: selectedElement}" 
  [ndcDynamicComponent]="selectedElement.component" 
  [ndcDynamicOutputs]="{newItemEvent: create}">
</ndc-dynamic>

This is my error:

ERROR TypeError: this.myMethod is not a function
  at Object.create [as newItemEvent] .....

Well this is the event emitter so yeah there is no method "myMethod".

CodePudding user response:

You're passing a method of the component class as an argument to ndcDynamicOutputs.

[ndcDynamicOutputs]="{newItemEvent: create}"

Inside the create method, you access this.

create() {
  this.myMethod()
}

The thing is, when you pass the method as an argument, it doesn't have the this context from the class anymore. this is going to have another value. So you have two options here:

The first one is to attach this using the bind function.

getCreateMethod() {
  return this.create.bind(this);
}
[ndcDynamicOutputs]="{newItemEvent: getCreateMethod() }">

Another option would be to refactor your create method so it doesn't access this, but maybe this isn't feasible.

  • Related