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 ...
The JavaScript spread operator ( ... ) allows us to quickly copy all or part of an existing array or object into another array or object.
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.
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.
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)"...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With