[英]Create sub-components in angular?
我想知道在angular中創建小組件的可能性是什么,可以在解析數據時顯示出來。 假設我們有一個文件(例如在 json 中):
[{
"name":"John",
"surname:"Doe",
"references":[{
"surname": "One"},{
"surname": "Two"}]
}]
所以,我想創建一個以“姓氏”節點為目標的組件,盡管它在樹中很深。 你能建議一種實現它的方法嗎? 提前致謝!
為了解決這個問題,我創建了一個組件,它可以與您需要的任何鍵一起使用(不僅是姓氏)。
關鍵組件.ts
import {
Component,
ContentChild,
Input,
OnChanges,
TemplateRef
} from "@angular/core";
@Component({
selector: "key-component",
templateUrl: "./key.component.html"
})
export class KeyComponent implements OnChanges {
@Input() json: Object;
@Input() key: string;
@ContentChild(TemplateRef)
template: TemplateRef<any>;
items: Array<any>;
ngOnChanges() {
// If the key or the JSON change, revaluate items
if (this.key && this.json)
this.items = this.getElementsWithSelectedKey(
this.objectDeepKeys(this.json)
);
}
// Get all the values that has the key given by Input
getElementsWithSelectedKey(keys: Array<String>) {
return keys
.filter((x: String) => x.endsWith(`.${this.key}`) || x === this.key)
.map(x => {
let currValue = this.json;
for (let str of x.split(".")) {
currValue = currValue[str];
}
return currValue;
});
}
// Finds all the keys for every sub-objects in depth
objectDeepKeys(obj: Object) {
return Object.keys(obj)
.filter(key => obj[key] instanceof Object)
.map(key => this.objectDeepKeys(obj[key]).map(k => `${key}.${k}`))
.reduce((x, y) => x.concat(y), Object.keys(obj));
}
}
key.component.html
<ng-container *ngTemplateOutlet="template; context: { $implicit: items }"></ng-container>
這個組件得到一個 json 來檢查(在你的情況下是整個數組)和一個要尋找的鍵(在你的情況下是“姓氏”)。 它檢查 json 中的每個鍵,並使用給定鍵將其找到的所有值的數組保存到屬性items
中。
現在你只需要選擇你的模板(你必須在key.component
的標簽之間編寫一個ng-template
)並獲取上下文( let-items
創建一個變量items
,其中包含來自屬性items
的元素到key.component
)隨心所欲地改變你的看法。
示例: app.component.html
<key-component [json]="myJSON" key="surname">
<ng-template let-items>
<surname-component *ngFor="let item of items" [surname]="item">
</surname-component>
</ng-template>
</key-component>
您可以使用幾個 JSON 查看整個代碼,以便在此Stackblitz上進行測試
我不知道'角度中的小組件'是什么意思,但如果你想從 json 文件中得到 map 響應,你可以使用 class:
export class People {
name: string,
surname: string,
references: othersurname[]
}
export class othersurname {
surname: string
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.