Cloned elements cannot be submitted in Angular4

前提是你 提交于 2019-11-29 12:22:35

This is intended behavior because all ngModel's you defined inside ng-template are not part of <form #myForm="ngForm" since angular has hierarchical dependency injection system.

I can offer you two options here:

1) move ng-template inside form tag

<form #myForm="ngForm" novalidate (ngSubmit)="save(myForm)">
  <div #container></div>
  <button type="submit">Submit</button>
  <ng-template #tpl>
    <div class="form-group">
      <input type="text" id="name" class="form-control" name="name" ngModel
             #name="ngModel">
      <input type="text" id="age" class="form-control" name="age" ngModel
             #age="ngModel">
      <button type="Button" >Remove</button>
    </div>
  </ng-template>
</form>

Stackblirz example

2) provide ControlContainer explicity on your component:

import { NgForm, ControlContainer } from '@angular/forms';

export function controlContainerFactory(component: AppComponent) {
  return component.ngForm;
}
@Component({
  selector: 'my-app',
  templateUrl: `./app.component.html`,
  viewProviders: [
    {
      provide: ControlContainer,
      useFactory: controlContainerFactory,
      deps: [AppComponent]
    }
  ]
})
export class AppComponent {
  ...   
  @ViewChild('myForm') ngForm: NgForm;
  ...
}

Stackblitz example

See also

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!