我有一個Item這樣的物件:
{
name: string;
parent: Item;
}
我想顯示所有專案,直到父屬性為空。例子:
{
name: "child3",
parent: {
name: "child2",
parent: {
name: "child1",
parent: {
name: "parent",
parent: undefined
}
}
}
應該像這樣生成html:
<a>child3</a> <a>child2</a> <a>child1</a> <a>parent</a>
我怎樣才能做到這一點?
<a [...] *ngIf="item">{{ item.name }}</a>
<a [...] *ngIf="item.parent">{{ item.parent.name }}</a>
<a [...] *ngIf="item.parent.parent">{{ item.parent.parent.name }}</a>
[...]
類似的事情會起作用,但如果深度未知,則不會。
那么我怎樣才能撰寫一個完全做到這一點的模板呢?
uj5u.com熱心網友回復:
解決方案 1
您可以使用嵌套項(遞回)創建組件:
@Component({
selector: 'component',
template: `
<!-- Show name -->
<a href="">{{item.name}}</a>
<!-- Show parent -->
<component *ngIf="item.parent" [item]="item.parent">
</component>
`
})
export class Component {
@Input()
item: any;
}
只需在您的組件中使用它,例如:
const obj = {
name: "child3",
parent: {
name: "child2",
parent: {
name: "child1",
parent: {
name: "parent",
parent: undefined
}
}
}
<component[item]="obj">
</component>
解決方案 2
將是通過一個物件,并制作一個名稱陣列。例如:
const obj = {
name: "child3",
parent: {
name: "child2",
parent: {
name: "child1",
parent: {
name: "parent",
parent: undefined
}
}
}
}
const getNames = (obj) => {
let currentObject = obj;
const names = [];
while (true) {
if (!currentObject) return names;
names.push(currentObject.name);
currentObject = currentObject.parent;
}
}
// Here you will get ['child3', 'child2', 'child1', 'parent']
const names = getNames(obj);
// And in the template you can just in a for loop show them
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/348014.html
標籤:有角的
