0

I have a DatagridComponent which just displays some rows with data in it. This one can pass action bar items to this component as many as he wants, and pass a function with it which gets called when an items (it's simply a button) gets clicked:

DatagridComponent:

@Component({
  selector: 'llqa-datagrid',
  templateUrl: './datagrid.component.html',
  styleUrls: ['./datagrid.component.css']
})
export class DatagridComponent implements OnInit {

  constructor() {}

  @Input() actionBar: Array<{
    text: string,
    action: () => {}
  }>;
}

datagrid.component.html:

<div class="datagrid">
  <div class="datagrid-actionbar">
    <button *ngFor="let actionBarItem of actionBar"(click)="actionBarItem.action()">{{actionBarItem.text}}</button>
  </div>
</div>

ParentComponent

@Component({
  selector: 'llqa-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {

  constructor() {}

  actionBar = [
    {
      text: "Add",
      action: () => {
        this.add()
      }
    },
    {
      text: "Delete",
      action: () => {
        this.delete()
      }
    }
  ];

  add(): void {
    // some code
  }

  delete(): void {
    // some code
  }
}

parent.component.html:

<llqa-datagrid [actionBar]="actionbar"></llqa-datagrid>

My Problem is, the function gets called, but loses the context of ParentComponent. So this would be the DatagridComponent. I made researches and found a way using @Output() with an EventEmitter, but this won't work in my case since the function I want to call is a property of an object. And since one should be able to add as many actionBar items as he wants, I can't just define @Output() properties, am I right?

So, how can I solve my problem?

onetwo12
  • 2,359
  • 5
  • 23
  • 34
nintschger
  • 1,786
  • 5
  • 30
  • 45

1 Answers1

0

I would pass actual grid instance in each action like this

@Input() actionBar: Array<{ text: string, action: (grid: DatagridComponent) => {} }>;

In parent

actionBar = [ { text: "Add", action: (grid) => { grd.add() } }, { text: "Delete", action: (grid) => { grid.delete() } } ];

I like this way because you are getting types information and there is no magical this reference.

Andzej Maciusovic
  • 4,306
  • 1
  • 29
  • 40