Cloned items cannot be represented in Angular4

I have a template with two for.eg name and age fields that should be cloned and added 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 didn’t get the form value after the form was submitted, and I also need to delete the cloned elements when I click the "Delete" button.

+1
source share
1 answer

This is the intended behavior because all the ngModel you define internally ng-templateare not part <form #myForm="ngForm", because angular has a hierarchical dependency injection system.

I can offer you two options:

1) move ng-templateinside the tagform

<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) ControlContainer :

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

.

+1

Source: https://habr.com/ru/post/1688870/


All Articles