2017-07-08 6 views
0

Hallo allerseits Ich mache eine „dinamic“ Form mit kantigem, und ich habe einige Probleme, die Werte zu erhalten, dass die Eingabe in Form, mein Code:Angular 2 - NgForm null, wenn ein Formular einreichen

HTML

<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)" *ngFor="let con of controls" novalidate> 
    <div class="form-group" *ngIf = "con.type != 'submit'"> 
    <label for="{{con.id}}">{{con.label}}</label> 
    <input [(ngModel)]="con.name" type="{{con.type}}" class="{{con.class}}" name="{{con.id}}"> 
</div> 
<input *ngIf = "con.type == 'submit'" type="submit" class="{{con.class}}" value={{con.label}}> 
</form> 

Komponente:

import { Component ,Input} from '@angular/core'; 
import { NgForm } from '@angular/forms'; 


@Component({ 
    selector: 'form-tag', 
    templateUrl: './form.html', 
}) 

export class FormComponent { 
    @Input() controls: any[]; 

    onSubmit(sub: NgForm) 
    { 
     console.log(sub.email); 
    } 
} 

das Problem ist, dass, wenn ich die Form console.log vorlegen (sub.email); Rückgabe eines leeren Objekts

Antwort

0

Da Sie ngForm verwenden, handelt es sich um eine vorlagengesteuerte Form und nicht um eine reaktive. In Vorlage getrieben Formen müssen Sie myForm.value zu onSubmit() übergeben:

onSubmit(myForm.value) 

auch aus dem Code Probe, es ist nicht klar, was con ist.

0

Ich bin nicht wirklich wirklich sicher, was Sie versuchen zu tun, aber es scheint, als ob Sie über Kontrollen mit dem <form> Tag statt nur mit dem div.form-group und dem <input /> selbst schleifen.

Vielleicht wrap diejenigen in einem <ng-template /> und Schleife durch sie und nicht die <form>-Tag?

So etwas wie folgt aus:

<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)" novalidate> 
    <ng-template *ngFor="let con of controls"> 
     <div class="form-group" *ngIf="con.type != 'submit'"> 
     <label for="{{con.id}}">{{con.label}}</label> 
     <input [(ngModel)]="con.name" type="{{con.type}}" class="{{con.class}}" name="{{con.id}}" /> 
    </div> 
    <input *ngIf="con.type == 'submit'" type="submit" class="{{con.class}}" [value]="con.label" /> 
</form>