问题描述
我需要使用绑定将一组值传递给组件,例如
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[];
...
}
但是,似乎 Angular 将其视为 string
/string[1]
(在实际项目中,数组是一个路由,我需要将此路由传递给具有 [routerLink]
指令的组件).
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 根本不处理:
You need to wrap the property with []
otherwise it is not processed by Angular at all:
[data]="[1, 2, 'test']"
您的示例似乎从组件内部设置了 data
.这不是绑定的工作方式.你可以用你的组件做的是 <my-component [data]="[1, 2, 'test']"></my-component>
从外部传递数据到您的组件.
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.
这篇关于如何从组件模板将数组作为 Input() 传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!