Я пытаюсь создать mat-option с вложенной структурой mat-option на основе объекта JSON. Я пытался создать * ngFor вместе с каналом, чтобы проходить через структуру JSON. Поэтому при выборе опции «Актер» я бы хотел создать другие поля опций для элементов в Акторе и так далее. Однако он создает только «Actor» -опцию, а затем появляется ошибка: «Не удается прочитать свойство 'elements' of undefined». Так что каким-то образом выполнение структуры JSON во время * ngFor не работает так, как я хочу. Что мне не хватает?
Мой HTML
<div *ngFor="let choice of choices; let i = index">
<mat-form-field [ngStyle]="{'margin-left.px': 15*i}">
[value] = "selections?selections[i]:undefined">
<mat-option *ngFor="let child of choice.elements | keys"
{{child.name}}
</mat-option>
</mat-select>
</mat-form-field>
</div>
Мой тс + JSON + труба:
selections: string[] = [];
this.incidentTree =
[{"_id": {"$oid": "5e9aa4041c9d44000054070f"},
"Source":
[{"name": "Actor",
"id": 0,
"elements": [
{"name": "Individual",
"id": 0,
"elements": [
{"name": "Outsider",
"id": 0},
{"name": "Insider",
"id": 1},
{"name": "Trusted Insider",
"id": 2},
{"name": "Pirvileged Insider", "id": 3}]},
{"name": "Group",
"id": 1,
"elements": [
{"name": "Ad hoc",
"id": 0},
{"name":"Established",
"id": 1}]},
{"name": "Organzation",
"id": 2,
"elements": [
{"name": "Competitor",
"id": 0},
{"name":"Supplier",
"id": 1},
{"name": "Partner",
"id": 2},
{"name": "Customer",
"id": 3}]},
{"name": "Nation State",
"id":3}]}]}]}]
constructor() { }
ngOnInit() {
this.choices[0] = this.incidentTree
}
My pipe keys:
import { Pipe, PipeTransform } from '@angular/core';
import { Source } from '../_classes/source';
@Pipe({
name: 'keys'
})
export class KeysPipe implements PipeTransform {
transform(value: any): any[] {
if(value) {
let dataArr = []
let keyArr: any[] = Object.keys(value)
// loop through the object,
// pushing values to the return array
keyArr.forEach((key: any) => {
console.log(key)
console.log(value[key])
dataArr.push(value[key]);
});
console.log(dataArr)
// return the resulting array
return dataArr;
}
}
}