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

后端 未结 3 479
耶瑟儿~
耶瑟儿~ 2021-02-04 23:38

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

@Component({
    selector: \'my-component\',
    template: \'
相关标签:
3条回答
  • 2021-02-05 00:23

    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.

    0 讨论(0)
  • 2021-02-05 00:25

    Normally you only use input when the component is nested within another component.

    So in another component, something like: <my-component [data]= ...>

    0 讨论(0)
  • 2021-02-05 00:27

    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>
    
    0 讨论(0)
提交回复
热议问题