【问题标题】:How to preserve two-way-binding using ngTemplateOutlet context (Angular7)如何使用 ngTemplateOutletcontext (Angular 7) 保留双向绑定
【发布时间】:2019-10-15 11:24:37
【问题描述】:

我需要设置一些配置表格,它们将动态显示在屏幕上。逻辑背后的对象嵌套很深,所以我需要对其结构做出反应(例如使用 ngFor)。 由于对象内不同层上的内容可以具有相同的表示形式,因此我试图将输入字段外包为模板。 当在一些 for 循环之后我调用我的模板化 HTML,使用上下文传递实际值时,数据的双向绑定在模板中不起作用。 看来,显然传递的是值而不是引用。传递键等在这里也不是选项,因为对象内容是复杂和动态的,这就是为什么我需要从 ng-template 进行输入绑定。

例如在 component.ts 中设置一个对象

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

在component.html中插入:

<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>

我在这里缺少什么? 在此先感谢您的帮助!

【问题讨论】:

    标签: angular angular-ngmodel two-way-binding ng-template


    【解决方案1】:

    而不是传递值传递整个对象像

    <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

    【讨论】:

    • 那么问题来了,我将丢失关于价值路径的信息。例如。在原始我有类似的东西: viewOption.value.specifications[tab.id].value -> 所以它是高度动态的,我也不能传递多达 4 个不同的键,因为在其他层上可能有更多或视图找到我想要呈现的价值。
    • 你能解释哪些信息?。同样使用值,你将无法绑定,因为你知道你传递的是一个值而不是引用
    • 哈!毕竟,您的解决方案并没有那么错误,当我只通过 viewOption.value.specifications[tab.id] 并在我的模板中执行 value.value 时,绑定是正确的。所以我似乎没有完全理解这里的基本概念。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2021-11-18
    • 2021-06-10
    • 1970-01-01
    • 2020-09-12
    • 2011-09-12
    • 1970-01-01
    • 2019-03-05
    • 2017-04-29
    相关资源
    最近更新 更多