简体   繁体   English

如何从组件模板将数组作为Input()传递?

[英]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, eg 我需要使用绑定将值的数组传递给组件,例如

@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). 但是,Angular似乎将其​​视为string / string[1] (在实际项目中,数组是一条路由,我需要将此路由传递给具有[routerLink]指令的组件)。

How do I go about this? 我该怎么办?

You need to wrap the property with [] otherwise it is not processed by Angular at all: 您需要使用[]包装属性,否则Angular根本不会处理它:

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

Your example seems to set data from inside the component. 您的示例似乎是从组件内部设置data 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. 您可以使用组件<my-component [data]="[1, 2, 'test']"></my-component>将数据从外部传递到您的组件。

So lets's start from here... in Angular 2+ all input will pass down a string if they don't get brackets around... 因此,让我们从这里开始...在Angular 2+中,如果输入中没有括号,所有输入将沿字符串传递...

So there are 2 ways to pass down your values... 因此,有两种方法可以传递您的价值观...

if you write it like this: '<div data="[1, 2, 'test']"' 如果您这样写: '<div data="[1, 2, 'test']"'

you basically get it as "[1, 2, 'test']" (as string)... 你基本上得到它为“ [1、2,'test']”(作为字符串)...

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}}' 您的操作方式是传递字符串的一种好方法,您也可以使用插值并将其与javascript混合,然后再传递给它,例如“ 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... 因此要将其作为Array或任何javascript none值传递给您,您需要像这样在输入周围使用[]

<div [data]="[1, 2, 'test']"></div>

Normally you only use input when the component is nested within another component. 通常,仅当组件嵌套在另一个组件中时才使用输入。

So in another component, something like: <my-component [data]= ...> 因此,在另一个组件中,例如: <my-component [data]= ...>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM