I want to pass an array to a function from component template.
This is 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 ...
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:
(click)="doCommand(item)"
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments