4

I need to setup some configuration forms, which will be shown on screen dynamically. The object behind the logic is deeply nested, so I need to react to its structure (e.g. using ngFor). Since content on different layers inside the object can have the same presentation I am trying to outsource input-fields as templates. When, after some for-loops I call my templated-HTML, passing the actual value using context, two-way-binding for data does not work within the template. It seems, that obviously the value is passed and not the reference. Passing keys etc. also is no option here since the objects content is complex and dynamic, which is why I need to make input bind from ng-template.

E.g. in component.ts setup an object

test = {time:"08:00"};

In component.html insert:

<div>
  {{ test.time }}
  <input type="time" [(ngModel)]="test.time"> <!-- works as expected, value changes on input-->
  <ng-template *ngTemplateOutlet="tmplInputTime; context: { value:test.time }"></ng-template>
</div>

<ng-template #tmplInputTime let-value="value">
    <input type="time" [(ngModel)]="value" > <!-- value not changing on input-->
</ng-template>

What am I missing here? Thanks in advance for help on this one!

Sabselol
  • 43
  • 1
  • 5

1 Answers1

4

Instead of passing the value pass whole object something like

<div>
  {{ test.time }}
  <ng-template *ngTemplateOutlet="tmplInputTime; context: { value:test}"></ng-template>
</div>

<ng-template #tmplInputTime let-value="value">
    <input type="time" [(ngModel)]="value.time" > <!-- value not changing on input-->
</ng-template>

working demo

jitender
  • 10,238
  • 1
  • 18
  • 44
  • Well the problem is then, that I will loose information on the path to the value. E.g. in the originial I have something like that: viewOption.value.specifications[tab.id].value -> so it is highly dynamic and I cannot pass up to 4 different keys also, since on other layers there might be more or view to find the value I want to present. – Sabselol Oct 15 '19 at 11:31
  • which information can you explain?.Also using value only you will not be able to bind as you know you are passing a value not the reference – jitender Oct 15 '19 at 11:32
  • Ha! Your solution wasn't that wrong after all, when I only pass viewOption.value.specifications[tab.id] and do value.value in my template the binding is correct. So it seems I did not fully understand the underlying concept here. Thank you very much! – Sabselol Oct 15 '19 at 12:10