Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass an array as Input() from the component template?

I need to pass an array of values to a component using binding, e.g.

@Component({     selector: 'my-component',     template: '<div data="[1, 2, 'test']"></div> }) export class MyComponent {     @Input() data: any[];     ... } 

However, it seems Angular treats this as string/string[1] (in the actual project the array is a route and I need to pass this route on to a component which has the [routerLink] directive).

How do I go about this?

like image 963
Thorsten Westheider Avatar asked Jul 04 '16 06:07

Thorsten Westheider


People also ask

How do I move an array from one component to another?

To pass an array as a prop to a component in React, wrap the array in curly braces, e.g. <Books arr={['A', 'B', 'C']} /> . The child component can perform custom logic on the array or use the map() method to render the array's elements. Copied!

How NgFor works in angular?

NgFor is a structural directive, meaning that it changes the structure of the DOM . It's point is to repeat a given HTML template once for each value in an array, each time passing it the array value as context for string interpolation or binding.


2 Answers

You need to wrap the property with [] otherwise it is not processed by Angular at all:

[data]="[1, 2, 'test']" 

Your example seems to set data from inside the component. This is not how binding works. What you can do with your component is <my-component [data]="[1, 2, 'test']"></my-component> to pass data from the outside to your component.

like image 139
Günter Zöchbauer Avatar answered Sep 17 '22 12:09

Günter Zöchbauer


So lets's start from here... in Angular 2+ all input will pass down a string if they don't get brackets around...

So there are 2 ways to pass down your values...

if you write it like this: '<div data="[1, 2, 'test']"'

you basically get it as "[1, 2, 'test']" (as string)...

The way you doing is a good way for passing down strings, and you can also use interpolation and mix it with javascript before passing it down like 'Angular {{version}}'

So to pass it down as an Array or any javascript none-sting value, you need to use [] around your input like this...

<div [data]="[1, 2, 'test']"></div> 
like image 44
Alireza Avatar answered Sep 20 '22 12:09

Alireza