Не удается получить доступ к переданной объектной переменной в повторно используемом ng-шаблоне
Цикл по объекту JSON, чтобы отобразить его как HTML в моем шаблоне компонента. Повторное использование встроенного ng-шаблона для вывода HTML.
С первой итерации я не могу получить доступ к свойствам Ojbect на level
так как это undefined
однако выходная HTML-подобная древовидная структура создается точно так же, как и JSON. Похоже, я не передаю переменную oject в правильном порядке.
JSON
{ "content": [
{
"tag": "paragraph",
"html": "\r\n",
"children": [
{
"tag": "header",
"level": "1",
"html": "\r\n91\/439\/EC Driving Licences"
},
{
"tag": "header",
"level": "2",
"html": "\r\nANNEX II - chapter II"
}
]
},
{
"tag": "br"
},
{
"tag": "paragraph",
"children": [
{
"tag": "table",
"html": "\r\n",
"children": [
{
"tag": "tr",
"children": [
{
"tag": "td",
"html": "II ."
},
{
"tag": "td",
"html": "\r\nMember States may implement the appropriate measures to ensure that drivers who have lost the knowledge, skills and behaviour as described under points 1 to 9 can recover this knowledge and these skills and will continue to exhibit such behaviour required for driving a motor vehicle.",
"children": [
{
"tag": "br"
},
{
"tag": "br"
},
{
"tag": "list",
"type": "disc",
"html": "\r\n",
"children": [
{
"tag": "li",
"html": "Recognise traffic dangers and assess their seriousness;"
},
{
"tag": "li",
"html": "Have sufficient command of their vehicle not to create dangerous situations and to react appropriately should such situations occur;"
},
{
"tag": "li",
"html": "Comply with road traffic regulations, and in particular those intended to prevent road accidents and to maintain the flow of traffic;"
},
{
"tag": "li",
"html": "Detect any major technical faults in their vehicles, in particular those posing a safety hazard, and have them remedied in an appropriate fashion;"
},
{
"tag": "li",
"html": "Take account of all the factors affecting driving behaviour (e.g. alcohol, fatigue, poor eyesight, etc.) so as to retain full use of the faculties needed to drive safely;"
},
{
"tag": "li",
"html": "Help ensure the safety of all road users, and in particular of the weakest and most exposed by showing due respect for others."
}
]
}
]
}
]
}
]
}
]
}
]
}
шаблон
<div *ngFor="let rootLevel of jsonHTML; let i = index;">
<span *ngIf="rootLevel.tag">{{i}} [{{rootLevel.tag}}]</span {{rootLevel.html}}
<ng-container *ngTemplateOutlet="nextLevelTemplate; context: { level: rootLevel.children, index: i }">
</ng-container>
</div>
<ng-template #nextLevelTemplate let-level="level" let-i="index">
<span *ngIf="level && level.tag">[{{level.tag}}]</span><span *ngIf="level && level.html">[{{level.html}}]</span>
[tag]{{level?.tag}}[/tag]
[html]{{level?.html}}[/html]
-{{level | json}}-
<div *ngFor="let nextLevel of level; let i = index;">
<ng-container *ngTemplateOutlet="nextLevelTemplate; context: { level: nextLevel.children, index: i }">
</ng-container>
</div>
</ng-template>
Выход
0 [paragraph]
0 -[object Object],[object Object]-
0 [tag][/tag] [html][/html] --
1 [tag][/tag] [html][/html] --
1 [br] 1 [tag][/tag] [html][/html] --
2 [paragraph] 2 [tag][/tag] [html][/html] -[object Object]-
0 [tag][/tag] [html][/html] -[object Object]-
0 [tag][/tag] [html][/html] -[object Object],[object Object]-
0 [tag][/tag] [html][/html] --
1 [tag][/tag] [html][/html] -[object Object],[object Object],[object Object]-
0 [tag][/tag] [html][/html] --
1 [tag][/tag] [html][/html] --
2 [tag][/tag] [html][/html] -[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]-
0 [tag][/tag] [html][/html] --
1 [tag][/tag] [html][/html] --
2 [tag][/tag] [html][/html] --
3 [tag][/tag] [html][/html] --
4 [tag][/tag] [html][/html] --
5 [tag][/tag] [html][/html] --
Вывод и снимок экрана следующего узла JSON
"children": [
{
"tag": "header",
"level": "1",
"html": "\r\n91\/439\/EC Driving Licences"
},
{
"tag": "header",
"level": "2",
"html": "\r\nANNEX II - chapter II"
}
]
Как вы можете видеть, в массиве есть 2 элемента, шаблон перебирает его дважды, но tag
а также html
свойства не могут быть доступны.
Это проблема с областью видимости, что ng-template не может быть использован таким образом?
1 ответ
Ответ на мой вопрос: рекурсивные ссылки на ng-шаблоны
Действительно ограниченный вопрос. Это, очевидно, все о том, как правильно обойти сферу.
<!-- Define the recursive template. -->
<ng-template #nodeTemplateRef let-node>
<div class="node" [class.node--selected]="( node === selectedTreeNode )">
<a (click)="selectNode( node )" class="node__label">
{{ node.label }}
</a>
<div *ngIf="node.children.length" class="node__children">
<!-- Invoke the recursive template. -->
<ng-template
ngFor
[ngForOf]="node.children"
[ngForTemplate]="nodeTemplateRef">
<!--
NOTE: The "$implicit" property of the ngFor context is what will
be made available to the template ref's implicit let-node binding.
-->
</ng-template>
</div>
</div>
</ng-template>
<ng-template
[ngTemplateOutlet]="nodeTemplateRef"
[ngTemplateOutletContext]="{ $implicit: data.root }">
</ng-template>
<p class="note">
<em>Ng-For Template Rendering</em>
</p>
... директивы ngFor успешно смогли рекурсивно отобразить шаблон ngTemplate, в котором он был определен.
При использовании директивы ngFor нет способа явно передать объект "context" - директива ngFor неявно передает объект ngForContext в качестве контекста шаблона. Это означает, что моя директива ng-template должна использовать "неявный" экспорт контекста ngFor в качестве привязки шаблона "let-node".
В этом случае это не проблема, так как я хочу передать только одно значение. Но для большей гибкости мы можем отказаться от директивы ngFor и просто использовать другой ng-шаблон для рекурсивного рендеринга шаблона (почти так же, как мы используем экземпляр ng-template для инициации рекурсии)...