克隆的元素无法在Angular4中提交 [英] Cloned elements cannot be submitted in Angular4

查看:83
本文介绍了克隆的元素无法在Angular4中提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模板,其中有两个字段,例如名称和年龄,需要克隆并附加到同一容器中.我使用以下代码实现了这一点.

I have a template with two fields for.eg name and age, that needs to cloned and appended to the same container. I achieved this using the following code.

html文件

<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>
<div>Some element</div>
<form #myForm="ngForm" novalidate (ngSubmit)="save(myForm)">
<div #container>

</div>
<button type="submit">Submit</button>
</form>
<button (click)="gettemplate()">Add Template</button>

<pre>{{myForm.value | json}}</pre>


TS文件


TS file

@ViewChild('container', { read: ViewContainerRef }) _vcr;
@ViewChild('tpl') tpl;

 gettemplate(){
  this._vcr.createEmbeddedView(this.tpl);
}
save(formvalue:NgForm){
   console.log(formvalue.value);
}

但是提交表单后我没有得到表单值,并且我还需要在单击删除"按钮时删除克隆的元素.

but I did not get the form values after submitting the form and also I need to remove the cloned elements on clicking Remove button.

推荐答案

这是预期的行为,因为您在ng-template内部定义的所有ngModel都不是<form #myForm="ngForm"的一部分,因为angular具有分层的依赖注入系统.

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)在form标记内移动ng-template

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

Stackblirz example

2)在您的组件上明确提供ControlContainer:

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

Stackblitz example

另请参见

这篇关于克隆的元素无法在Angular4中提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆