如何从组件模板将数组作为Input()传递? [英] How can I pass an array as Input() from the component template?

查看:223
本文介绍了如何从组件模板将数组作为Input()传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用绑定将值的数组传递给组件,例如

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()传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆