如何在角度组件模板中使用Spread Operator

M_F*_*and 5 angular

我想从组件模板将数组传递给函数。
这是我的工具栏:
toolbar.component.html

<div *ngFor="let item of items">
   <button mat-mini-fab [style.color]="item.color" 
    (click)="item.command(...item.commandParams)">
     <i class="material-icons">{{item.icon}}</mat-icon>
   </button>
 </div>
Run Code Online (Sandbox Code Playgroud)

工具栏.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-toolbar',
  templateUrl: './toolbar.component.html',
  styleUrls: ['./toolbar.component.scss']
})
export class ToolbarComponent implements OnInit {
  items: ToolBarItem[]

  constructor() {
  }

  ngOnInit() {
  }
}

export class ToolBarItem {
  icon = 'border_clear';
  color: string;
  command: () => void;
  commandParams: any[];
}
Run Code Online (Sandbox Code Playgroud)

在这里,我想使用各种命令来初始化工具栏的项目。
主要

...
items: [
        {
          icon: 'mode_edit',
          color: 'blue',
          command: (name, family) => {
            console.log('editClick!' + name + family);
          },
          commandParams: ['mohammad', 'farahmand'],
        },
        {
          icon: 'delete',
          color: 'red',
          command: () => {
            console.log('deleteClick!');
          },
        }
      ],
...
Run Code Online (Sandbox Code Playgroud)

但是我得到这个错误:

错误:模板解析错误:解析器错误:意外令牌。在...的[item.command(... item.commandParams)]中的第14列

Gre*_*eek 5

It's unlikely that you're going to get this syntax to work in a template (there are many valid typescript constructs that don't work in templates).

You could write a helper method in the component instead, that takes the item as an argument, and then makes the appropriate call, as in, for example:

public doCommand(item: ToolbarItem): void {
  item.command(...item.commandParams);
}
Run Code Online (Sandbox Code Playgroud)

and then change your template to:

(click)="doCommand(item)"
Run Code Online (Sandbox Code Playgroud)