Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Spread Operator in angular component template

Tags:

angular

I want to pass an array to a function from component template, the following is the code for my toolbar:

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>

toolbar.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[];
}

Here I want to init items of toolbar with varies commands.
main.ts

...
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!');
          },
        }
      ],
...

But i get this error:

Error: Template parse errors: Parser Error: Unexpected token . at column 14 in [item.command(...item.commandParams)] in ...

like image 280
M_Farahmand Avatar asked Mar 15 '18 14:03

M_Farahmand


People also ask

What is the use of spread operator in Angular?

The JavaScript spread operator ( ... ) allows us to quickly copy all or part of an existing array or object into another array or object.

What does !: Means in Angular?

Means safe navigation operator. From Docs. The Angular safe navigation operator (?.) is a fluent and convenient way to guard against null and undefined values in property paths. Here it is, protecting against a view render failure if the currentHero is null.

Can you use spread operator on objects?

Spread syntax can be used when all elements from an object or array need to be included in a new array or object, or should be applied one-by-one in a function call's arguments list.


1 Answers

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);
}

and then change your template to:

<button (click)="doCommand(item)"...
like image 151
GreyBeardedGeek Avatar answered Sep 22 '22 21:09

GreyBeardedGeek