Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular (4): pass a class object from child to parent component

I can pass a class object like Person into a child component from parent component without any problems. But I would like to also manipulate that object in child component and pass it back to parent component.

This is the child component class:

export class ActionPanelComponent {
  @Input('company') company: Company;
  @Output() notify: EventEmitter = new EventEmitter();

  constructor() {
  }

  public deleteCompany() {
    console.log('display company');
    console.log(this.company);
    // FIXME: Implement Delete
    this.company = new Company();
  }

  public onChange() {
    this.notify.emit(this.company);
  }

}

This is the html of this component (excerpt):

<div class="row" (change)="onChange()">
  <div class="col-xs-2">
    <button md-icon-button >
      <md-icon>skip_previous</md-icon>
    </button>
  </div>

This is the parent component class (excerpt):

  public onNotify(company: Company):void {
    this.company = company;
  }

And the parent component html (excerpt):

<action-panel [company]="company" (notify)="onNotify($event)"></action-panel>

I am doing something wrong because I cannot pass my company object inside the .emit and nothing works.

What is the correct way of achieving two way object binding between components? Thanks in advance!

like image 921
Deniss M. Avatar asked Jan 30 '23 16:01

Deniss M.


1 Answers

You were missing the type on the initialization of the EventEmitter.

You could use the Output binding to implement the two way object binding:

Child component (ts)

export class ActionPanelComponent {
    @Input('company') company: Company;
    @Output() companyChange: EventEmitter = new EventEmitter<Company>();

    constructor() {
    }

    public deleteCompany() {
       console.log('display company');
       console.log(this.company);
       // FIXME: Implement Delete
       this.company = new Company();
    }

    public onChange() {
       this.companyChange.emit(this.company);
    }

}

Parent component (html)

<action-panel [(company)]="company"></action-panel>

So like this you don't need to declare an extra function onNotify. If you do need the onNotify function, use another name for the output binding:

export class ActionPanelComponent {
    @Input('company') company: Company;
    @Output() notify: EventEmitter = new EventEmitter<Company>();

    constructor() {
    }

    public deleteCompany() {
       console.log('display company');
       console.log(this.company);
       // FIXME: Implement Delete
       this.company = new Company();
    }

    public onChange() {
       this.notify.emit(this.company);
    }

}
like image 92
Aleics Avatar answered Feb 03 '23 03:02

Aleics