如何在Angular2中绑定列表? [英] How to bind a list in Angular2?
问题描述
我正在尝试创建一个嵌套的树视图.
I'm trying to create a nested treeview.
@Component({
selector: "myItem",
template: `
<li *ngIf="!Array.isArray(data)"> {{data.text}} </li>
<ul *ngIf="Array.isArray(data)">
<myItem *ngFor="let x of data" [(data)] = "x.data"> </myItem>
</ul>
`
})
export class MyItemComponent {
static root = true;
data: any;
constructor() {
if (MyItemComponent.root) {
this.data = [
{ text: "foo" },
[{ text: "bar" }, { text: "foo" }]
];
MyItemComponent.root = false;
}
}
}
错误是
无法绑定到数据",因为它不是已知的本机属性("ta.text}} ] [data] ="x.data">):MyItemComponent
Can't bind to 'data' since it isn't a known native property ("ta.text}} ][data] = "x.data"> "): MyItemComponent
如何实现删除按钮?模板应如下所示:
how can I implement a delete button? The template should look like:
<li *ngIf="!Array.isArray(data)"> {{data.text}} <button (click)="clicked()"> delete me</button> </li>
<ul *ngIf="Array.isArray(data)"> <button (click)="clicked()"> delete me</button>
<myItem *ngFor="let x of data" [(data)] = "x.data"> </myItem>
</ul>
什么是 click
函数?
推荐答案
向组件添加自定义属性
我认为这将更好地解决您的问题:要能够绑定到较新版本的Angular2中的自定义属性,您必须使用 [attr.custom]
语法.参见本问题和
I think this will solve your issue better: to be able to bind to custom attributes in the newer versions of Angular2 you must use [attr.custom]
syntax. See this issue and this one for more information.
看看@yurzui的评论-它会将您链接到正在工作的Plunker
如果要向指令添加自定义输入
如果您想将数据输入到指令中,可以使用Angular2的 Input
来完成.例如
export class MyItemComponent {
//...
@Input('attribute') attribute: any;
//...
}
这将确保Angular在组件中知道从何处获取数据.
This will ensure that in your Component Angular will know where to look to get the data.
感谢@GünterZöchbauer进行澄清:)
这篇关于如何在Angular2中绑定列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!