Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

angular - Cloned elements cannot be submitted in 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 file

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...