Angular 如何动态添加角度组件内容?
我想用板条箱装一个嵌套层Angular 如何动态添加角度组件内容?,angular,angular7,Angular,Angular7,我想用板条箱装一个嵌套层 @Component({ selector: 'items-collection', template: '<ng-content></ng-content>' }) export class ItemsComponent { } @组件({ 选择器:'项目集合', 模板:“” }) 导出类项目组件{ } HTML的用法如下: <items-collection> <item [name]="item
@Component({
selector: 'items-collection',
template: '<ng-content></ng-content>'
})
export class ItemsComponent {
}
@组件({
选择器:'项目集合',
模板:“”
})
导出类项目组件{
}
HTML的用法如下:
<items-collection>
<item [name]="item-1"></item>
<item [name]="item-2"></item>
<item [name]="item-3"></item>
</items-collection>
但是,如果我为items集合设置一个json源数据,那么数据将动态追加
@Component({
selector: 'items-collection',
template: '<ng-content></ng-content>'
})
export class ItemsComponent {
private jsondata:any[] = [
{"name": "item-8"},
{"name": "item-9"},
{"name": "item-15"}
]
}
<items-collection source="jsondata">
<item [name]="item-1"></item>
<item [name]="item-2"></item>
<item [name]="item-3"></item>
</items-collection>
@组件({
选择器:'项目集合',
模板:“”
})
导出类项目组件{
私有jsondata:任何[]=[
{“名称”:“第8项”},
{“名称”:“第9项”},
{“名称”:“第15项”}
]
}
这可能吗?在ItemsComponent中
@Component({
selector: 'items-collection',
template: `<ng-container *ngFor=let data of jsonData">
<item [name]="data.name"></item>
</ng-container>`
})
export class ItemsComponent {
@Input('source') jsonData: any[] = [];
}
@组件({
选择器:'项目集合',
模板:`您可以将
与正常的*ngFor
:
@Component({
selector: 'items-collection',
template: `
<ng-content></ng-content>
<item *ngFor="let item of source" [name]="item.name"></item>
`
})
export class ItemsComponent {
@Input() source?: { name: string }[];
}
@组件({
选择器:'项目集合',
模板:`
`
})
导出类项目组件{
@输入()源?:{name:string}[];
}
确保使用输入绑定
<items-collection [source]="jsondata">
<item [name]="'item-1'"></item>
<item [name]="'item-2'"></item>
<item [name]="'item-3'"></item>
</items-collection>
为什么*ngFor在这种情况下不起作用?@khush如果想要列表中的一些默认项
<items-collection [source]="jsondata">
<item [name]="'item-1'"></item>
<item [name]="'item-2'"></item>
<item [name]="'item-3'"></item>
</items-collection>