1

I try to use a PrimeNG SplitButton.

@Component({
  selector: 'test',
  template: `
  
  <ul>
    <li *ngFor="let l of lst">{{ l }}
        <p-splitButton label="foo" (onClick)="foo (l)" [model]="menu"></p-splitButton>
    </li>
  </ul>
`
})


export class TestComponent
{
    lst : string [] = ["abc", "123", "xyz"];
    menu : MenuItem [] = [{label: "bar", command: (e) => { this.bar (e) }}];

    foo (x)
    {
        console.log ("foo", x);
    }
    
    bar (x)
    {
        console.log ("bar", x);
    }
}

How can I pass the value of the iteration of lst (l) to bar? I want use it the same way as I do it with foo but not sure how to get the argument down to menu.

chris01
  • 10,921
  • 9
  • 54
  • 93

2 Answers2

1

You can use the onDropdownClick event to store the index of the splitButton you're currently opening and then use it inside bar, like this:

@Component({
  selector: 'test',
  template: `
  <ul>
    <li *ngFor="let l of lst">{{ l }}
        <p-splitButton label="foo" (onClick)="foo(l)" (onDropdownClick)="dropdownClickHandler(l)" [model]="menu"></p-splitButton>
    </li>
  </ul>
`
})
export class TestComponent
{
    lst : string [] = ["abc", "123", "xyz"];
    menu : MenuItem [] = [{label: "bar", command: () => { this.bar() }}];

    currentIndex: number;

    foo (x)
    {
        console.log("foo", x);
    }
    
    bar ()
    {
        console.log("bar", this.currentIndex);
    }

    dropdownClickHandler(index) {
        this.currentIndex = index;
    }
}
Shai
  • 3,659
  • 2
  • 13
  • 26
1

I figured out this.

<p-splitButton label="foo" (onClick)="foo (l)" [model]="getMenu (l)"></p-splitButton>



getMenu (x):any
{
    return [{label: "bar", command: (e) => { this.bar (x) }}];
}

Is it bad style to cover it with a function in Angular??

chris01
  • 10,921
  • 9
  • 54
  • 93
  • 1
    Technically, it's not great. This method runs over and over again after every little thing you do. Try placing a logging breakpoint inside this method in DevTools. You'll see that everything you do causes this method to run, pretty sure that even moving your mouse will cause it to run. If it's a small project or if performance is not an issue, it's not that bad. Otherwise, I wouldn't recommend it. You can read about it [here](https://medium.com/showpad-engineering/why-you-should-never-use-function-calls-in-angular-template-expressions-e1a50f9c0496). – Shai Jul 14 '22 at 12:22
  • If your real code uses `ChangeDetectionStrategy.OnPush` it will be better, but the method will still run each time change detection happens, which includes every time you click on something inside the component this template belongs to. – Shai Jul 14 '22 at 12:24