简体   繁体   中英

Angular EventEmitter parent This equals with the EventEmitter

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 class="form">
    <mat-form-field class="form__input">
      <input matInput placeholder="Name"  name="name" type="name"  [(ngModel)]="item.name">
    </mat-form-field>

    <div class="form-actions">
      <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".

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.

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