【问题标题】:Angular 2 custom form control with multiple inputs in template-driven wayAngular 2 自定义表单控件,以模板驱动的方式具有多个输入
【发布时间】:2017-01-15 21:33:14
【问题描述】:

我的领域模型是

vm = { 
  name: 'John Doe', // input in parent form
  account: { // child component with 2 inputs
    acc1: '08', 
    acc2: '6523' 
  } 
};

父表单是模板驱动的,看起来像

<form #form="ngForm" name="form" novalidate (ngSubmit)="submit(form)">
  <label>Name</label>
  <input type="text" name="name" [(ngModel)]="vm.name" />
  <my-child name="account" [(ngModel)]="vm.account"></my-child>
  <button type="submit">Submit</button>
</form>
<pre>form.value={{form.value | json}}</pre>

子组件有 2 个用于 acc1 和 acc2 字段的输入,并使用 formGroup、formControlName 指令以模型驱动的方式编写。

正如您在this plunker 中看到的,域模型和子组件之间的双向绑定可以正常工作。我的意思是 vm.account 中的初始模型值显示在视图中,模型随着输入字段中的用户类型而更新。

我的问题:是否可以使用 ngModel 等以模板驱动的方式编写此子组件,以使其在父表单中以相同的方式工作?我不知道如何让子组件将视图更改传播到模型。

编辑:根据接受的答案,上面的 plunker 更新为显示 2 个组件,一个以响应方式,一个以模板驱动方式。

【问题讨论】:

    标签: angular angular2-forms


    【解决方案1】:

    我制作了实际上是嵌套的模板驱动表单。

    http://plnkr.co/edit/FUmAshW6NDIp44lVCe2y?p=preview

    我对你的 plunker 做了一点改动,主要改动在这里:

    template: `
        <form>
          <label>Account</label>
          <input type="text" name='acc1' [(ngModel)]="accountNumber.acc1"/>
          <input type="text" name='acc2' [(ngModel)]="accountNumber.acc2"/>
        </form>
        <pre>{{accountNumber | json}}</pre>
      `
    

    在 ControlValueAccessor 实现中:

      propagateChange = (_: any) => {
      }
      registerOnChange(fn: (value: any) => void) {
         this.propagateChange = fn;
      }
    
      registerOnTouched() {}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-29
      • 1970-01-01
      • 2019-08-20
      • 2022-01-27
      • 2017-03-31
      • 2017-01-30
      • 2016-04-26
      • 2018-10-26
      相关资源
      最近更新 更多